在单个mysql查询中获取组中的用户(仅允许)

时间:2014-07-21 17:19:42

标签: mysql sql left-join

从以下表格中,我必须根据以下逻辑获取指定组中允许的用户列表。

  • 案例1:所有用户在没有匹配时符合条件(没有记录) user_group表)。
  • 案例2:群组中匹配的用户(拥有 user_group表中的exclusion = 0)
  • 案例3:除以外的群组中的用户 否认(排除= 1)

MYUSER

user_id | user_name 
  1     |  a
  2     |  b
  3     |  c

MyGroup的

group_id | group_code
  1      |  G1
  2      |  G2
  3      |  G3

USER_GROUP

userid  | groupid | exclusion
  1     |   1     |  0
  1     |   2     |  0
  2     |   1     |  1 

这是适用于案例1和案例的查询。 3但案例2失败。

SELECT u.id, g.id, g.code, ug.exclusion FROM MyUser u
join MyGroup 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) 

因此,在具有排除= 1的记录的情况下,该记录获得并且其他组添加具有空条件。问题是空字段也被添加为排除= 0,这根本不需要。

请建议我们是否只使用单个查询获取给定群组的用户列表

预期结果:

g1(a,c), g2(a,b,c), g3(b,c) 

1 个答案:

答案 0 :(得分:0)

这应该可以使用,或者接近它。

select u.user_id, g.group_id, g.code
from MyGroup g
    cross join users u 
    left join user_group allowed ON u.user_id = allowed.user_id AND g.group_id = allowed.group_id AND allowed.exclusion = 0
    left join user_group allowbydefault ON u.user_id = allowbydefault.user_id
where (allowed.user_id is not null OR allowbydefault.group_id is null)
-- and g.group_id = 1 -- uncomment to get everyone authorized for group #1
-- and u.user_id = 35 -- uncomment to get every group that user #35 is authorized for
group by u.user_id, g.group_id, g.code

我使用SQL Server来测试这个,但这至少应该为你提供另一个攻击点。