簡體   English   中英

MySQL-從聯接表中查找與所有行匹配的行

[英]MySQL - Find rows matching all rows from joined table

表1:軌道

表2:單詞表

表3:N:M音軌有單詞(trackwords)

找到所有單詞的所有曲目。

當前查詢看起來像:

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 | 
+----+-------------+-------+--------+-----------------------+---------+---------+----------------+---------+-------------+

但是查詢需要很長時間。 有什么建議可以加快查詢速度嗎?

如果您只想查找包含所有單詞的音軌,則左聯接毫無意義。 我假設( trackidwordid )相結合的獨特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)上的索引。

您的問題集非常類似於為StackOverflow或Del.icio.us這樣的項目存儲標簽的過程。

文章標簽:數據庫模式提出了幾種解決方案,其中包括@ ChssPly76的想法。

如果將其分解為兩個查詢,可能會更快。 首先,將單詞和trackword結合起來,為您提供所需的所有trackid。 然后回到跟蹤表並執行以下操作:

WHERE t.id IN(...trackids here...)

但是根據上面的查詢,您要返回的是已經來自tw.trackid的t.id。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM