Im struggling to articulate this, let alone execute in in MYSQL. How Do I return the userId X where userId.X and permissionId in (1,2,3,4,5,6,7,8) ?
The below example should return 6.
MariaDB [mailserver]> select * from user2permission;
+--------------+--------+
| permissionId | userId |
+--------------+--------+
| 1 | 5 |
| 1 | 6 |
| 2 | 6 |
| 2 | 7 |
| 3 | 6 |
| 4 | 6 |
| 5 | 6 |
| 6 | 6 |
| 7 | 6 |
| 8 | 6 |
+--------------+--------+
This kind of query can be written with the use of Group By clause and counting the instance as per the filteration applied in where clause
SELECT userId
FROM user2permission
WHERE permissionId IN (1,2,3,4,5,6,7,8)
GROUP BY userId
HAVING COUNT(*) = 8
You want to only show users that have an entry for all required permissions. Two solutions spring to mind:
select *
from users
where userid in (select userid from user2permission where permissionid = 1)
and userid in (select userid from user2permission where permissionid = 2)
...
and
select userid,
from user2permission
group by userid
having count(case when permissionid = 1 then 1 end) > 0
and count(case when permissionid = 2 then 1 end) > 0
...
And when I say "spring" to mind, I mean exactly that = without much thinking :-) Rizwan's aggregation solution is what you should use.
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.