Advanced search: roles and multiple taxonomies

I was able to solve my problem with this query, although I bet it can be more efficient (I just couldn’t figure out how to do it.)

SELECT DISTINCT p.* FROM wp_posts p 
LEFT JOIN wp_usermeta um ON p.post_author = um.user_id 
LEFT JOIN wp_postmeta pm ON p.ID = pm.post_id 
INNER JOIN ( 
    SELECT txrm.object_id FROM wp_term_relationships AS txrm 
    LEFT JOIN wp_term_taxonomy txm ON txrm.term_taxonomy_id = txm.term_taxonomy_id 
    LEFT JOIN wp_terms trm ON txm.term_id = trm.term_id 
    WHERE txm.taxonomy = 'mediums' 
    AND ( trm.name LIKE '%Acrylic%' ) 
    GROUP BY txrm.object_id 
    HAVING count(trm.name) = 1 
) AS trm ON p.ID = trm.object_id 
INNER JOIN wp_term_relationships txrk ON p.ID = txrk.object_id 
INNER JOIN wp_term_taxonomy txk ON txrk.term_taxonomy_id = txk.term_taxonomy_id 
INNER JOIN ( 
    SELECT txrk.object_id FROM wp_term_relationships AS txrk 
    LEFT JOIN wp_term_taxonomy txk ON txrk.term_taxonomy_id = txk.term_taxonomy_id 
    LEFT JOIN wp_terms trk ON txk.term_id = trk.term_id 
    WHERE txk.taxonomy = 'keywords' 
    AND ( trk.name LIKE '%Landscape%' ) 
    GROUP BY txrk.object_id 
    HAVING count(trk.name) = 1 
) AS trk ON p.ID = trk.object_id 
WHERE p.post_status="publish" 
AND p.post_type="gallery" 
GROUP BY p.ID 
ORDER BY p.post_date DESC 

So basically, I had to add an inner query for each taxonomy, in which it sends back a list of term relationships that match the criteria, but by grouping them, I don’t get duplicates.

error code: 523