最近我遇到了一个有趣的问题。让我们添加一些表,即 User、Group 和它们的 Join 表 User_Group。以下是表格的虚拟表示
用户
user_id | user_name
1 | a
2 | b
3 | c
组
group_id | group_code
1 | G1
2 | G2
3 | G3
用户组
userid | groupid | exclusion
1 | 1 | 0
1 | 2 | 0
2 | 1 | 1
好吧,问题是获取他有权访问的用户的组列表。 组中用户访问的一般假设是:
- 如果用户在 User_group 连接表中没有条目,则该用户可以访问 所有组(即 G1、G2 和 G3)
- 如果用户在 User_Group 中有条目 exclusion 0 那么该用户只能访问该组(用户 1 有 在 G1 和 G2 中访问)
- 如果用户在 User_Group 中具有排除条目 1 然后该用户在该组中没有访问权限,但他可以访问 other 所有其他组(用户 2 仅在 g1 上被拒绝并且应该有 在 G2 和 G3 访问)
这是为案例 1 和 3 获取结果但在案例 2 中失败的查询。
SELECT g.id, g.code, ug.user_groups_id, ug.exclusion FROM group g
LEFT JOIN user_group ug ON ug.group_id = g.id
AND ug.user_id = 1 -- works for user 2 and 3 but fails for user 1
WHERE (ug.exclusion = 0 OR ug.exclusion IS NULL)
请建议我们是否可以仅使用单个查询来获取组列表
最佳答案
有趣的问题。
您可以通过生成所有用户和所有组的列表(使用交叉连接
)来解决这个问题。然后使用 left join
匹配回已知的组列表。那么逻辑是:
- 情况 1 是在没有匹配项时使用所有组。
- 情况 2 是仅使用匹配的组。
- 情况 3 是仅使用不匹配的组。
这里是查询:
select u.userid,
(case when max(ug.exclusion) is null -- all groups
then group_concat(g.groupcode)
when max(ug.exclusion) = 0 -- only those included
then group_concat(case when ug.groupid is not null then g.groupcode end)
when max(ug.exclusion) = 1 -- exclude these
then group_concat(case when ug.groupid is null then g.groupcode end)
end)
from users u cross join
groups g left join
user_groups ug
on u.userid = ug.userid and g.groupid = ug.groupid
group by u.userid;
请注意,这仅在聚合中使用排除标志——基本上假设它在 user_groups
中的所有行上都是相同的。事实上,这个标志可以在 user
级别而不是在 user_groups
级别。这个假设既与样本数据一致,也与问题的解释一致。
关于mysql - 使用单个 mysql 查询为用户获取组(仅允许),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823088/