MySQL链接和/或搜索

时间:2018-04-09 14:29:11

标签: mysql sql

这是我的表

+-------+-------------+
|user_id|permission_id|
+-------+-------------+
|1      |4            |
+-------+-------------+
|1      |5            |
+-------+-------------+
|1      |6            |
+-------+-------------+
|2      |4            |
+-------+-------------+
|2      |5            |
+-------+-------------+
|3      |4            |
+-------+-------------+
|3      |6            |
+-------+-------------+

我想要一个搜索查询,我可以搜索多个权限并获取具有此类权限的所有user_id。 示例:

users with permissions 4 AND 5, will be: user_id 1, 2
users with permissions 4 AND 5 AND 6, will be: user_id 1
users with permissions 4 AND (5 OR 6), will be: user_id 1, 2, 3

提前谢谢!:)

2 个答案:

答案 0 :(得分:2)

您可以使用group byhaving

select user_id
from userpmissions
group by user_id

然后有条款是:

having sum(permission_id = 4) > 0 and sum(permission_id = 5) > 0
having sum(permission_id = 4) > 0 and sum(permission_id = 5) > 0 and sum(permission_id = 6) > 0
having sum(permission_id = 4) > 0 and sum(permission_id in (5, 6)) > 0 

我将这些类型的查询称为“set-within-sets”查询,因为您正在查找每个用户中的权限集。我发现group byhaving是解决这些查询的最灵活方式。我应该注意,对于特定的组合,可能会有更有效的方法。

答案 1 :(得分:2)

您可以像这样使用子查询(并且像逻辑操作那样任意组合它们)。

SELECT DISTINCT user_id
FROM permissions
WHERE user_id IN (
    SELECT user_id FROM permissions WHERE permission_id = 4
) AND user_id IN (
    SELECT user_id FROM permissions WHERE permission_id = 5
)