将用户和组添加到其他组,并使用sql将所有层次结构置于顶部

时间:2014-12-14 07:40:57

标签: sql

我想制作一个组策略,我可以将用户分配给组和组到其他组,这样我就创建了一个数据库表

table groups { Type, EntityID, GroupID }

用户的类型可以是1,组的类型可以是2

例如,如果我有一个类型为1且entityID = 1groupid = 2的实体 这意味着id 1的用户属于id 2的组,依此类推,类型2的组相同

当某个群组有groupID = NULL时,这是一个根群组,这意味着该群组没有父群组。

我想写一个select查询,它返回用户所属的组的所有层次结构

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

任何建议

1 个答案:

答案 0 :(得分:1)

使用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