I have 3 tables : users, roles and roles_users (roles_users is a relational table with 2 columns, user_id and role_id)
A user can have many roles, through the roles_users table.
How can I build a select query that will not select a user, if he has a specific role.
To illustrate :
-
a super admin user has the super admin , admin, login and publisher roles.
-
an admin user has the admin, login and publisher roles.
-
a publisher user has the login and publisher roles.
I want to select all the users that do not have the super admin role.
In other words, if a user has the super admin role, then do not select it.
How can I achieve this in SQL ?
Edit : Here is the query that worked for me at the end : (thanks to András Ottó’s answer)
SELECT DISTINCT(users.id), users.*
FROM users
INNER JOIN roles_users on users.id = roles_users.user_id
INNER JOIN roles ON roles_users.role_id = roles.id
WHERE NOT EXISTS(SELECT roles_users.user_id FROM roles_users
WHERE roles_users.user_id = users.id AND roles_users.role_id = 2)
In Sql Server on in Oracle you can try:
Here is an SQL Fiddle.