用于自联接的SQL查询

时间:2013-10-03 11:49:59

标签: sql-server

enter image description here

嗨,我有上表结构的成员表。在这里,我们可以通过列GroupID ..

轻松查询MemberID

示例...对于GroupID = 1,我们将得到结果

ObjectType    MemberID
-----------------------------
  user         1
  user         2
  group        2
  group        3

但是,我需要的是,我想列出嵌套成员(表示组成员的成员....对于group = 2,group = 3)

预期结果应该是这样的

ObjectType    MemberID
-----------------------------
  user         1
  user         2
  group        2
  group        3
  user         4
  group        3
  user         7

任何人都可以帮我写这个案例的查询吗?。

3 个答案:

答案 0 :(得分:0)

为什么需要JOIN?如果我没弄错的话,你正在处理1张桌子?

SELECT ObjectType, MemberID
From   Table
Group by GroupId, ObjectType, MemberID
Order by MemberID

答案 1 :(得分:0)

实现此目的的一种方法是使用递归common table expressionCTE 像这样的东西

;with cte as 
(
    select *, groupid as mastergroup,1 as level from yourtable 
    union all       
    select t1.memberid, t1.objecttype, null, cte.mastergroup, level+1
    from cte 
        inner join yourtable t1
            on t1.groupid=cte.memberid
    where cte.objecttype='g'
) 
select * from cte
where mastergroup=1

但是,从您的表结构中,不清楚如何定义组的成员。

答案 2 :(得分:0)

你可以在这里使用CTE

    ;WITH tableResult (ObjectType, ObjectType)
AS
(
-- Anchor member definition
SELECT TD.ObjectType, TD.ObjectType
FROM yourtableAS TD   
    UNION ALL
-- Recursive member definition
SELECT TD.ObjectType, TD.ObjectType
FROM TaskDependency AS TD
INNER JOIN tableResult AS TR
    on TD.groupid= TR.memberid 
        and TR.objecttype='group'
    )

--then select from this cte
Select * from tableResult