开发者

Checking if MySQL Database data does not exist

I have my songs set-up in my MySQL database.

Each song is is either assigned multiple locations or has no locations at all.

Only the songs that either have no locations assigned in the database or have the location assigned to the ones specified below should be pulled from the database.

Hopefully when you understand my query below it will make sense

SELECT s.* FROM roster_songs AS s 
    LEFT JOIN roster_songs_locations AS sl ON sl.song_id = s.id 
    WHERE EXISTS (
        SELECT sl2.* FROM roster_songs_locations AS sl2 WHERE s.id != sl2.song_id
    ) OR ( 
       sl.location_id = '88fb5f94-aaa6-102c-a4fa-1f05bca0eec6' 
       OR 
       sl.location_id = '930555b0-a251-102c-a245-1559817ce81a'
    ) 
    GROUP BY s.id

The query almost works except it pulls out of the data开发者_开发知识库base songs that are assigned to sl.location_id's that aren't specified in the above query. I think it has something to do with my EXISTS code picking them up...

Any ideas how I can get this to work?


If there is no location associated with the location, sl.location_id will be null, so just add that to your WHERE:

SELECT s.* FROM roster_songs AS s 
LEFT JOIN roster_songs_locations AS sl ON sl.song_id = s.id 
WHERE
   sl.location_id = NULL
   OR  
   sl.location_id = '88fb5f94-aaa6-102c-a4fa-1f05bca0eec6' 
   OR 
   sl.location_id = '930555b0-a251-102c-a245-1559817ce81a'
) 
GROUP BY s.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜