MySQL - Find rows matching all rows from joined table

后端 未结 3 342
無奈伤痛
無奈伤痛 2021-01-27 12:36

Table 1: Tracks

Table 2: Wordlist

Table 3: N:M Track has Words (trackwords)

Find all tracks which have all the words.

currently the query looks l

相关标签:
3条回答
  • 2021-01-27 12:55

    Would probably be faster if you broke this up into two queries. First, a join of the words and trackwords to net you all the trackids you need. Then go back to the track table and do:

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

    but based on the query above all you're returning is t.id which you have from tw.trackid already.

    0 讨论(0)
  • 2021-01-27 12:58

    Your problem set is very much like that of storing tags for an item like StackOverflow or Del.icio.us does.

    The article Tags: Database schemas proposes several solutions, among them @ChssPly76's idea.

    0 讨论(0)
  • 2021-01-27 13:00

    There's no point in left joins if you're only looking for tracks that have all the words. I'm assuming that (trackid,wordid) combination is unique in 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
    

    This query would benefit from indexes on wordlist(word), trackwords(trackid,wordid) and track(id).

    0 讨论(0)
提交回复
热议问题