2

我有 3 个表:用户、组和成员。
用户有 ID 和名称。
也有 Id 和 Name。
Membership有 id、GroupId 和MemberId

问题是MemberId既可以是用户也可以是组

我想要的是获取用户是否直接属于的所有组。

为此,我使用 CTE,如下所示:

WITH MyGroups AS(
select *,1 as GLevel from [Group] as g where g.id IN (SELECT groupId FROM Membership m where m.memberId='MYID')

UNION ALL

select g.*,2 from [Group] g inner JOIN MyGroups my on my.id=g.id --where g.id IN (SELECT groupId FROM ACLTests.dbo.Membership m where m.groupid=g.id))

Select * from MyGroups

但我要超过 100 个递归级别......有人可以帮忙吗?

样本数据:

用户表:
ID----------|标题---------
myUser1 |John
myUser2 |Leo

组表:
ID---------|标题---------
myG1 。. .|Group1
我的G2 。. .|组2

会员表:
ID | 组ID | 会员编号
01 | 我的G1... . .| 我的用户1 02
| 我的G1... . .| 我的G2
03 | 我的G2... . .| 我的用户2

MyUser1的预期结果:Group1 MyUser2
预期结果:Group1,Group2(G2 是 g1 的成员,User2 是 G2 的成员,所以 User2 也是 G1 的成员)

4

2 回答 2

1

这是您需要的查询。如果确实需要,请确保您确实需要option (maxrecursion 0),然后将其添加到下面的查询中。

    SET NOCOUNT ON
    DECLARE @User TABLE
    (
        id      sysname NOT NULL
        ,title  sysname NOT NULL
    )
    DECLARE @Groups TABLE
    (
        id      sysname NOT NULL
        ,title  sysname NOT NULL
    )
    DECLARE @Membership TABLE
    (
        id      INT NOT NULL
        ,groupid    sysname NOT NULL
        ,memberid   sysname NOT NULL
    )

    INSERT INTO @User( id, title ) SELECT 'myuser1','John' UNION ALL SELECT 'myuser2','Leo'
    INSERT into @Groups( id, title ) SELECT 'myG1','Group1' UNION ALL SELECT 'myG2','Group2'
    INSERT into @Membership( id, groupid, memberid ) SELECT 1,'myG1','myuser1' UNION ALL SELECT 2,'myG1','myG2' UNION ALL SELECT 3,'myG2','myuser2'



    DECLARE @SearchUsergroup sysname='myUser2'
    ;WITH mType(id,title,mType)
    AS
    (
        SELECT id,title,'user' AS mType
        FROM @User
        UNION ALL
        SELECT id,title,'Group' AS mType
        FROM @Groups
    ),
    Ugroups(id,mType,mLevel)
    AS
    (
        SELECT groupid,'Group' as mType, 1 AS mLevel
        FROM @Membership
        WHERE memberid = @SearchUsergroup

        UNION ALL
        SELECT ms.groupid,'Group' as mType, ug.mLevel+1 AS mLevel
        FROM mType mt
        JOIN Ugroups ug
            ON mt.id=ug.id AND ug.mType='Group'
        JOIN @Membership ms
            ON ms.memberid=ug.id
    )
    SELECT id AS GroupID,mLevel AS MembershipLevel
    FROM Ugroups

在此处输入图像描述

于 2013-10-25T16:58:05.240 回答
0

option (maxrecursion 0)在查询末尾添加。

UPD。

WITH MyGroups AS (
    select g.id, 1 as GLevel
    from Group as g
    where g.id IN (
        SELECT groupId
        FROM Membership m
        where m.memberId = 'MyUser2'
    )
    UNION ALL
    select m.GroupId, my.GLevel + 1
    from Membership m
    inner JOIN MyGroups my on m.memberId=my.id
)

Select * from MyGroups
于 2013-10-25T14:06:15.160 回答