Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to find users not having specific group id in join table

I have a table named jos_user_usergroup_map that has 2 columns: user_id and group_id

A user can be a member of several groups and thus has several rows in this table, each with the group ID, e.g.

user_id|group_id
62     | 1
62     | 4
62     | 12
108    | 1

I want to find all the user_id's where that is not having a group_id = 12, but it's giving me a headache...

In the above example, I should find only user_id = 108

Any ideas how to do this? Any help is appreciated.

Thanks

like image 408
Dyvel Avatar asked Jan 04 '16 13:01

Dyvel


3 Answers

Try this:

SELECT DISTINCT A.user_id
FROM jos_user_usergroup_map A 
LEFT OUTER JOIN jos_user_usergroup_map B ON A.user_id = B.user_id AND B.group_id = 12 
WHERE B.user_id IS NULL;
like image 179
Saharsh Shah Avatar answered Oct 06 '22 18:10

Saharsh Shah


Use post aggregation filtering

SELECT user_id FROM jos_user_usergroup_map 
GROUP BY user_id
HAVING SUM(group_id=12)=0
like image 42
Mihai Avatar answered Oct 06 '22 16:10

Mihai


I would try something like:

SELECT DISTINCT `user_id`
FROM `jos_user_usergroup_map`
WHERE `user_id` NOT IN (
    SELECT `user_id` 
    FROM `jos_user_usergroup_map` 
    WHERE `group_id` = 12
)

Or using exists (Which is probably faster than in):

SELECT DISTINCT `user_id`
FROM `jos_user_usergroup_map`
WHERE NOT EXISTS (
    SELECT `user_id` 
    FROM `jos_user_usergroup_map` 
    WHERE `group_id` = 12 AND `user_id` = `jos_user_usergroup_map`.`user_id`
)

However, please note that whilst these solutions are logically easy to understand, the JOIN based answers are normally much faster in practice.

like image 21
JosephGarrone Avatar answered Oct 06 '22 18:10

JosephGarrone