MySQL - 从连接表中查找匹配所有行的行

标签 mysql join

表 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/

相关文章:

r - 窗口(又名滚动)与 data.table 连接

ruby-on-rails - Rails 3. 获取相关模型的属性

MySQL 比较当前行之前的日期范围内的数据并对其进行 count()

php - 如何禁用 SELECT QUERY 对结果进行自动排序

Mysql统计有多少答案是正确的

Mysql加入请求

mysql查询找出不存在的用户

mysql - 重新启动 mysql 时刷新 mysql-relay-bin 日志文件

mysql - 社交网络应用程序数据库设计 : how can I improve this schema?

join - Apache Solr - 作为 super 查询参数的子查询计数