Custom query to get terms from post ids

It is not advised to make use of custom SQL queries if there are functions in WordPress that already does the job.

To accomplish this, you can simply make use of wp_get_object_terms(). The first parameter $object_ids takes a string or an array of object ID’s. In your case, you can make use of an array of your post ID’s. This will retrieve all the terms assosiated with the given post/s.

Here is an example

$terms = wp_get_object_terms( array(394,530),  'category' );
if ( ! empty( $terms ) ) {
    if ( ! is_wp_error( $terms ) ) {
        foreach( $terms as $term ) {
            ?><pre><?php var_dump($term); ?></pre><?php 
        }
    }
}

This will give you the following output

object(stdClass)#494 (10) {
  ["term_id"]=>
  int(115)
  ["name"]=>
  string(8) "child-01"
  ["slug"]=>
  string(7) "child01"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(115)
  ["taxonomy"]=>
  string(8) "category"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(21)
  ["count"]=>
  int(2)
  ["filter"]=>
  string(3) "raw"
}