title: MySQL Query Retrieve Tags in TWO Categories (AND not OR) [WordPress Raw SQL]
body: <p>Struggling with this for a while</p>
  
  <pre><code>   SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, terms2.slug as tag_slug, t2.description as tag_desc
      FROM
          wp_posts as p1
          LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
          LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
          LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,
  
          wp_posts as p2
          LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
          LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
          LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id
      WHERE
      t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (224,229) AND
      t2.taxonomy = 'product_tag' AND p2.post_status = 'publish'
          AND p1.ID = p2.ID
      ORDER by tag_name
  </code></pre>
  
  <p>Line I am dealing with is this one:</p>
  
  <p><code>t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id IN (224,229) AND</code></p>
  
  <p>This works, but the <code>IN</code> clause acts as an <code>OR</code>--- so it is bringing back tags that are in either the <code>term_id</code> <code>224</code> or <code>229</code></p>
  
  <p>I am trying to make it so that it only returns tags that are in BOTH <code>224</code> and <code>229</code></p>
  
  <p>I've tried </p>
  
  <p><code>t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id = '224' AND
   t1.taxonomy = 'product_cat' AND p1.post_status = 'publish' AND terms1.term_id = '229' AND</code></p>
  
  <p>but it just returns an empty result...</p>
  
  <p>The only solution I have right now is to do two queries <code>terms1.term_id = '224'</code> for <code>224</code> and terms1.term_id = '229' for <code>229</code> and then use other logic to return the two matching.</p>
  
  <p>Is there a way to combine this into one query?</p>
  
  <p>Edit: See results of the IN query below (modified so that <code>terms1.term_id</code> is visible)</p>
  
  <p><a href="https://i.stack.imgur.com/OQtPa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQtPa.png" alt="enter image description here"></a></p>
  
  <p>As you can see <code>Gray</code> is only in 229 (and thus not part of the result set I am trying to return back)</p>