我想制定一种组策略,以便可以将用户分配给组,将组分配给其他组,因此我创建了一个数据库表
table groups { Type, EntityID, GroupID }
用户的类型可以是1,组的类型可以是2
例如,如果我有一个类型为1的实体,entityID = 1
并且groupid = 2
这意味着id 1的用户属于id 2的组,依此类推,对于type 2的组也是如此
当一个组具有groupID = NULL
根组时,这意味着该组没有父组。
我想编写一个选择查询,该查询返回用户所属组的所有层次结构
Groups
桌子
ID Type Entity GroupID
-----------------------
1 2 1 NULL
2 2 2 1
3 2 3 NULL
4 2 4 3
5 2 5 4
6 2 6 5
7 2 7 6
8 1 1 6
例如,最后一行包含一个用户,该用户属于组6,组6属于g5,g5属于g4,g4属于g3,g3是根组
因此,如果我运行查询,它应该返回这样的结果
Type EntityID GroupID
2 3 NULL
2 4 3
2 5 4
2 6 5
有什么建议
使用cte
只需复制下面的代码
WITH UserBelongTo (Type,EntityID,GroupID)
AS
(
select a.Type, a.EntityID, a.GroupID from Groups a
where a.EntityID in (select Groups.GroupID from Groups where EntityID=1 and Type=1)
and a.Type=2
union all
select a.Type, a.EntityID, a.GroupID from Groups a
inner join UserBelongTo c on c.GroupID=a.EntityID
where a.Type=2
)
select distinct * from UserBelongTo
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句