Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select users having required roles only

Tags:

sql

mysql

I have standard table with users->roles relations

user_id | role_id
----------------
1       |   1
1       |   2
1       |   3
2       |   1
2       |   3
3       |   1
3       |   2
4       |   1
4       |   2
4       |   3
4       |   4

For the clear comprehension

1: [1, 2, 3]
2: [1, 3]
3: [1, 2]
4: [1, 2, 3, 4]

I want to write a query returning users having only required roles. For example, if required roles are [1, 2, 3, 5] then only users 1, 2, 3 satisfy the condition because user 4 has the role 4 not required

like image 759
Nawa Avatar asked Feb 24 '26 04:02

Nawa


1 Answers

You can use correlated subquery

 select * from tablename a
 where not exists (select 1 from tablename b where a.user_id=b.user_id and role_id not in (1,2,3,5))
like image 73
Fahmi Avatar answered Feb 27 '26 03:02

Fahmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!