2

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 |
+--------------+--------+
Mark
  • 418
  • 3
  • 12
dom
  • 23
  • 3

2 Answers2

3

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
Rizwan
  • 2,369
  • 22
  • 27
0

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.

Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73