title: MySQL - Find rows matching all rows from joined table
body: <p>Table 1: Tracks</p>
  
  <p>Table 2: Wordlist</p>
  
  <p>Table 3: N:M Track has Words (trackwords)</p>
  
  <p>Find all tracks which have all the words.</p>
  
  <p>currently the query looks like:</p>
  
  <pre><code>SELECT DISTINCT t.id FROM track as t
  Left Join trackwords as tw ON t.id=tw.trackid
  Left Join wordlist as wl on wl.id=tw.wordid
  WHERE 
  wl.trackusecount&gt;0 
  group by t.id
  HAVING SUM(IF(wl.word IN ('folsom','prison','blues'),1,0)) = 3;
  </code></pre>
  
  <p>Which according to EXPLAIN is using all indexes neccessary:</p>
  
  <pre><code>+----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
  | id | select_type | table | type   | possible_keys         | key     | key_len | ref            | rows    | Extra       |
  +----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
  |  1 | SIMPLE      | t     | index  | PRIMARY               | PRIMARY | 4       | NULL           | 8194507 | Using index | 
  |  1 | SIMPLE      | tw    | ref    | wordid,trackid        | trackid | 4       | mbdb.t.id      |       3 | Using where | 
  |  1 | SIMPLE      | wl    | eq_ref | PRIMARY,trackusecount | PRIMARY | 4       | mbdb.tw.wordid |       1 | Using where | 
  +----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
  </code></pre>
  
  <p>But the query takes ages.
  Any suggestion to speedup the query?</p>