Skip to content
Advertisement

SQLite: how to exclude records in a database with join tables?

I have a database with a schema similar to:

Say they have the following data in them:

Artists:

artist_id artist_name
1 Bob
2 Shawn

Songs:

song_id song_name
1 one song
2 another song

song_artist:

song artist
1 1
1 2
2 2

Here, both Bob and Shawn are involved in one song, and only Shawn is involved in another song. Say I wanted to get the names of the songs where Shawn is involved, but not Bob. So, in this case it would be only another song. However, as to be expected, this query doesn’t work as it gives me both the songs:

song_name
1 one song
2 another song

This would be the result of the join table song_artist having multiple records for the same song, so even if a record with Bob‘s ID is excluded, there’s still another record without Bob‘s ID that gets included in the final result.

Here’s how I’ve found a workaround to this:

song_name
1 another song

Now, while this works as expected, as one can imagine, this becomes a long winded query once you have a lot more than a single join table. I also assume this is a very un-optimized query. My question is, what is a better way to do this kind of query?

Advertisement

Answer

First, add a WHERE clause in your query which filters out any other artists than Shawn and Bob.
Then use conditional aggregation and in the HAVING clause add the condition that Bob does not participate in the song (which leaves only Shawn):

See the demo.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement