Checking if MySQL Database data does not exist

Posted by Ben Sinclair on Stack Overflow See other posts from Stack Overflow or by Ben Sinclair
Published on 2010-05-11T11:01:26Z Indexed on 2010/05/11 11:04 UTC
Read the original article Hit count: 328

Filed under:

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 database 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?

© Stack Overflow or respective owner

Related posts about mysql