表1:曲目
表2:Wordlist
表3:N:M轨道有单词(跟踪词)
查找包含所有单词的所有曲目.
目前查询如下:
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>0
group by t.id
HAVING SUM(IF(wl.word IN ('folsom','prison','blues'),1,0)) = 3;
Run Code Online (Sandbox Code Playgroud)
根据EXPLAIN,使用所有索引是必要的:
+----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
| 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 |
+----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
Run Code Online (Sandbox Code Playgroud)
但查询需要很长时间.有什么建议可以加快查询速度吗?
如果你只是在寻找拥有所有单词的曲目,那么左连接就没有意义了.我假设(trackid,wordid)组合是独一无二的trackwords.
SELECT t.id
FROM track as t, trackwords as tw, wordlist as wl
WHERE t.id=tw.trackid
AND wl.id=tw.wordid
AND wl.trackusecount>0 /* not sure what that is - you have it in your query */
AND wl.word in ('folsom','prison','blues')
GROUP by t.id
HAVING count(*) = 3
Run Code Online (Sandbox Code Playgroud)
此查询将受益于wordlist(单词),trackwords(trackid,wordid)和track(id)上的索引.