简体   繁体   中英

mySQL query joining association table matching this AND this OR this

I need a little help. Not sure why I can't make sense of this one.

I have a table for songs, genre and an association between the two.

SONGS
song_id
song_name
active (0,1)

GENRE
genre_id
genre_name (rock,jazz,classical,newage,opera)

ASSOC
song_id
genre_id

I can do a simple search like this...

SELECT s.song_name, s.song_id
FROM (songs s)
LEFT JOIN assoc a ON s.song_id = a.song_id
WHERE s.active = 1
AND a.genre_id = 1

And a multi search like this.

SELECT s.song_name, s.song_id
FROM (songs s)
LEFT JOIN assoc a ON s.song_id = a.song_id
WHERE s.active = 1
AND (a.genre_id = 1 
   OR a.genre_id = 2)

BUT, what if I want to get 1 and 2 OR 3? This does not work.

SELECT s.song_name, s.song_id
FROM (songs s)
LEFT JOIN assoc a ON s.song_id = a.song_id
WHERE s.active = 1
AND a.genre_id = 1
AND (a.genre_id = 2 
   OR a.genre_id = 3)

Thanks in advance for help. I have a feeling I am just looking at this the wrong way.

Try this,

   SELECT s.song_name, s.song_id
    FROM (songs s)
    LEFT JOIN assoc a ON s.song_id = a.song_id
    WHERE s.active = 1
    AND (a.genre_id = 1
    OR a.genre_id = 2 
       OR a.genre_id = 3)

your where clause was wrong because

AND a.genre_id = 1 AND (a.genre_id = 2 OR a.genre_id = 3)

that's mean in one row you have two options

a.genre_id=1 and a.genre_id=1 or
a.genre_id=1 and a.genre_id=3

and you only have a genre_id per rows, so you can't not have 2 values in the same rows

SELECT s.song_name, s.song_id
FROM (songs s)
LEFT JOIN assoc a ON s.song_id = a.song_id
WHERE s.active = 1
AND (a.genre_id = 1
  AND a.genre_id = 2) 
OR a.genre_id = 3

I think this is what you're looking for

You can perform a self-join:

SELECT s.song_name, s.song_id
FROM   songs AS s
  JOIN assoc AS a1 ON a1.song_id = s.song_id AND a1.genre_id = 1
  JOIN assoc AS a2 ON a2.song_id = s.song_id AND a2.genre_id IN (2,3)
WHERE  s.active = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM