Is what i have:
SELECT users.*
FROM users INNER JOIN roles_users ON users.id = roles_users.user_id
WHERE roles_users.role_id IN (1)
GROUP BY users.id
HAVING COUNT(*) = 1
I would like to grab all the users that ONLY has one row, with role_id 1.
The above query grabs all the users that have a row with role_id 1, so it shows also those who have more rows with role_id 2, role_id 3 for example.
So how can i do WHERE roles_users.role_id IN (1) AND NOT in 2,3,4.. something?
Add an anti-join to exclude those users that also have other roles
The above is quite MySQL-specific as normally, you shouldn’t select columns that are not part of the
GROUP BYclause. Besides, maybe it is not best performing, asroles_usersis joined two times tousers. I don’t know if MySQL can optimise this.