2012-12-13 45 views
12

我有這樣的結構:

如何獲得父母的所有兒童,然後使用遞歸他們的孩子在查詢

<Unit> 
    <SubUnit1> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnit1/> 
    <SubUnit2> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnit2/> 
    ... 
    <SubUnitN> 
      <SubSubUnit1/> 
      <SubSubUnit2/> 
      ... 
      <SubSubUnitN/> 
    </SubUnitN/> 
</Unit> 

這個結構有3個級別:主力戶型,亞基和SubSubUnits。

我想選擇UnitId的所有孩子。
如果我按單位搜索,我必須得到所有的樹。
如果我通過SubUnit1搜索,我必須得到SubUnit1和SubUnit1的所有子代。
如果我搜索SubSubUnit2,我必須得到它自己。

這裏是我的嘗試:

with a(id, parentid, name) 
as (
select id, parentId, name 
    from customer a 
    where parentId is null 
union all 
    select a.id, a.parentid, a.Name 
    from customer 
    inner join a on customer.parentId = customer.id 
    ) 
select parentid, id, name 
from customer pod 
where pod.parentid in (
select id 
from customer grbs 
where grbs.parentid in (
select id 
from customer t 
where t.parentid = @UnitId 
)) 
union 
select parentid, id, name 
from customer grbs 
where grbs.parentid in (
select id 
from customer t 
where t.parentid = @UnitId 
) 
union 
select parentid, id, name 
from customer c 
where c.Id = @UnitId 
order by parentid, id 

我用3工會的話,那不是很好,但它的工作原理。案例結構將有N級,我如何得到正確的結果?

+0

看看這個答案:http://stackoverflow.com/questions/317322/optimized-sql-for-tree-structures – twoleggedhorse

回答

18
DECLARE @Id int = your_UnitId 
;WITH cte AS 
(
    SELECT a.Id, a.parentId, a.name 
    FROM customer a 
    WHERE Id = @Id 
    UNION ALL 
    SELECT a.Id, a.parentid, a.Name 
    FROM customer a JOIN cte c ON a.parentId = c.id 
) 
    SELECT parentId, Id, name 
    FROM cte 

演示上SQLFiddle

+0

它的工作原理!謝謝! – user1893999

+0

謝謝。此代碼是工作。 – Datta

相關問題