title: SQL query: Simulating an "AND" over several rows instead of sub-querying
body: <p>Suppose I have a "tags" table with two columns: <strong>tagid</strong> and <strong>contentid</strong>.  Each row represents a tag assigned to a piece of content.  I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.</p>
  
  <p>The "easy" way to do this would be (<em>pseudocode</em>):</p>
  
  <pre><code>select contentid from tags where tagid = 334 and contentid in (
      select contentid from tags where tagid = 338 and contentid in (
          select contentid from tags where tagid = 342
      )
  )
  </code></pre>
  
  <p>However, my gut tells me that there's a better, faster, more extensible way to do this.  For example, what if I needed to find the intersection of 12 tags?  This could quickly get horrendous.  Any ideas?</p>
  
  <p><strong>EDIT</strong>: Turns out that this is also covered in <a href="http://weblogs.sqlteam.com/jeffs/jeffs/archive/2007/06/12/60230.aspx" rel="noreferrer">this excellent blog post</a>.</p>