So my solution on this kind of problems where we have a very complex set of rules is to avoid doing new SQL just for my solution because if you have to explain it to a beginner it gets hairy.
My solution:
function get_term_union( $taxonomy, $tax_query, $post_type="post" ){
$args = array(
'post_type' => $post_type,
'tax_query' => $tax_query,
'fields' => 'ids',
);
$posts = new WP_Query( $args );
$terms = array();
foreach( $posts as $post_id ){
$terms = array_merge( $terms, wp_get_post_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) ) );
}
$terms = array_unique( $terms );
return $terms;
}
// Usage
$tax_query = array(
'relation' => 'AND',
array(
'taxonomy' => 'taxonomy_B',
'field' => 'slug',
'terms' => 'term_A',
),
array(
'taxonomy' => 'taxonomy_C',
'field' => 'slug',
'terms' => 'term_B',
),
);
// This will return you all the term id's for `taxonomy_A`
var_dump( get_term_union( 'taxonomy_A', $tax_query ) );
If this solution doesn’t fit your needs tell me and I will try to fix it.
My Best Regards,