I can’t tell here whether or not you have the WordPress API available to you. (Is this code that is being run from within an instance of WordPress, or is it being run by an external script on the WordPress database, without bootstrapping WordPress itself?)
If you have the WordPress API, it is easy to get a list of all posts that have a postmeta value with a given key. Thus:
<?php
$q = new WP_Query(array(
"meta_key" => "meta_key_i_want_to_find"
));
while ($q->have_posts()) : $q->the_post();
// Do something here. E.g.: $posts[] = get_the_ID(); to collect IDs
endwhile;
wp_reset_query();
// If you just collected above, now do something with it...
Again, if you have the WordPress API available to you, you can add a category to a post using wp_set_post_terms().
If you don’t have the WordPress API available to you, you can get a representation of the post data you need using:
-- Modify to SELECT all and only the fields you intend to use.
SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON
wp_posts.ID=wp_postmeta.post_ID WHERE (meta_key='meta_key_i_want_to_find');
Loop through the IDs, adding category relationships manually as you go along.