Reputation: 1775
Thanks for reading.
I have two sql tables. groups and group_members
groups table have group details. For example:
group_id - group_name
1 music
2 video
3 funny
And groupmembers have the subscribed users. For example
id - group_id - user_id
1 1 5
2 3 8
User 5 is member of music and user 8 is member of funny. I want to show to the user the group which he hasn't subscribed yet. In this case it should video and funny for the user 5
I tried this
SELECT gr.*, gm.* FROM groups gr
LEFT JOIN groupmembers gm
ON gm.group_id = gr.group_id
WHERE gm.user_id != 5
But it shows everything and duplicates some rows. I'm not even sure that should I use LEFT JOIN or something else.
What is the right approach to this?
Thank you!
Upvotes: 1
Views: 51
Reputation: 2120
You are just missing one condition (OR gm.user_id IS NULL
) in your query .
SELECT gr.group_name FROM groups gr
LEFT JOIN groupmembers gm
ON gm.group_id = gr.group_id
WHERE gm.user_id != 5 OR gm.user_id IS NULL;
http://www.sqlfiddle.com/#!2/0f6e59/17
Upvotes: 0
Reputation: 11142
SELECT gr.group_name
FROM groups gr
WHERE gr.group_id NOT IN (
SELECT gm.group_id
FROM groupmembers gm
WHERE gm.user_id = 5
)
That should do it, basically grab all of the group IDs the user belongs to, and then do a NOT IN
to exclude them. You could do it with a JOIN
but this is more readable in my opinion.
Upvotes: 2