I would like to grab all the users that ONLY have two roles, which are 1 and 4.
One user role is stored like this:
user_id role_id
54321 1
54321 4
54322 1
54323 1
How can i make a query, that grabs the user_id 54321, because it Only have two roles and these two are 1 and 4?
I can use WHERE role_id IN (1, 4) but this will also grab users that have other roles.
WHERE role_id IN (1, 4) GROUP BY user_ID HAVING COUNT(DISTINCT role_id) = 2
http://gregorulm.com/relational-division-in-sql-the-easy-way/
This is an example of a set-within-sets query. I like to solve these with group by
and having
because that is the most general approach:
select user_id
from user_roles ur
group by user_id
having sum(role_id = 1) > 0 and
sum(role_id = 4) > 0 and
sum(role_id not in (1, 4)) = 0;
The having
clause has three conditions. The first counts the number of times that role is 1, and the user_id
passes if there is at least one such role. The second does the same for 4. The last checks that there are no other values.
I like this structure because it is flexible. If the condition were 1 and 4 and others are allowed, you would just drop the third clause. If the condition were 1 or 4 and no others, then it would look like:
having (sum(role_id = 1) > 0 or
sum(role_id = 4) > 0
) and
sum(role_id not in (1, 4)) = 0;
SELECT u3.user_id
FROM t u1, t u2, t u3
WHERE u1.role_id = 1 AND u2.role_id = 4
AND u3.user_id = u1.user_id
AND u2.user_id = u1.user_id
GROUP BY u3.user_id HAVING COUNT(u3.role_id) = 2;
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.