表 1:轨道
表 2:单词表
表3:N:M Track has Words(跟踪词)
找到包含所有单词的所有轨道。
当前查询看起来像:
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;
根据 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 |
+----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+
但是查询需要很长时间。 有什么建议可以加快查询速度吗?
最佳答案
如果您只想查找包含所有单词的轨道,则左连接没有意义。我假设 (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
此查询将受益于 wordlist(word)、trackwords(trackid,wordid) 和 track(id) 上的索引。
关于MySQL - 从连接表中查找匹配所有行的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1242223/