简体   繁体   中英

Exclude results from mysql query results

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!

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.

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

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