Skip to content
Advertisement

Query to modify where clause to specify relation

I have 2 tables: users & user_roles

users:
id   name
1    John
2    Doe
user_roles:
user_id role
1       admin
1       finance
1       accounting
2       admin
2       finance
2       admin

I want to get the users that have admin & finance roles in the output(with distinct).

So the result will be only user with ID of 2 (Doe)

What is the best SQL solution for this?

Advertisement

Answer

Hi guys I found the solution. so it might help someone with the same problem with me

select u.id, u.name
from users u
INNER join user_roles ur on ur.user_id = u.id
group by u.id, u.name
having
    COUNT(DISTINCT(CASE WHEN ur.role IN ('admin', 'finance') THEN ur.role END)) = 2
    AND COUNT(DISTINCT(CASE WHEN ur.role NOT IN ('admin', 'finance') THEN ur.role END)) = 0
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement