2013-10-25 52 views
2

我有3個表:用戶,組和成員資格。
用戶有Id和Name。
也有Id和Name。
成員有ID,groupId和成員Id遞歸查詢重建對象圖

的事情是,成員Id既可以是用戶一組。

我想要的是直接獲取用戶所屬的所有組

要做到這一點我使用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 |約翰
myUser2 |獅子座

組表:
ID ---------- |標題---------
myG1。 。 。| Group1
myG2。 。 。| Group2

會員表:
ID | GROUPID | MEMBERID
01 | myG1 ..。 。 。| myUser1
02 | myG1 ..。 。 。| myG2
03 | myG2 ..。 。 。| MyUser2

預期的結果FOR 爲MyUser1:組別1
預期的結果FOR MyUser2:組1,組2(G2是g1的成員,並且用戶2是G2的成員,所以用戶2是也G1的成員)

+0

你有什麼問題呢?你可以請張貼一些樣本數據和預期的產出? – Rachcha

+0

@Rachcha編輯!檢查出來... – Leonardo

回答

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 

enter image description here

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 
+0

hummmm有趣...錯誤消失了,但現在我得到無盡的結果... – Leonardo

+0

您不指定遞歸查詢何時停止。看到我更新的答案。 – GriGrim