我正在努力表达这一点,更不用说在MYSQL中执行了。如何在(1,2,3,4,5,6,7,8)中返回userId.X和permissionId的userId X?
以下示例应返回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 |
+--------------+--------+
答案 0 :(得分:3)
这种查询可以使用Group By子句编写,并根据where子句中应用的过滤计算实例
SELECT userId
FROM user2permission
WHERE permissionId IN (1,2,3,4,5,6,7,8)
GROUP BY userId
HAVING COUNT(*) = 8
答案 1 :(得分:0)
您希望仅显示具有所有必需权限条目的用户。想到两种解决方案:
select *
from users
where userid in (select userid from user2permission where permissionid = 1)
and userid in (select userid from user2permission where permissionid = 2)
...
和
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
...
当我说“春天”时,我的意思是确切地说=没有太多思考:-) Rizwan的聚合解决方案就是你应该使用的。