2011-10-04 74 views
1

,我需要一路上升的水平爲1,並獲得 相應childID的紀錄,即209遞歸查詢找到基於最高級別和相應的childID的記錄 即71這裏的父記錄

對於前:

要找到71 childrecord:

級別4母公司 - 154,Level3的母公司 - 192,level2的母公司 - 209 或1級的孩子 - 209

209是需要的答案。

現在棘手的部分是最高級別是可變的。我上面顯示的查詢 不能正常工作,因爲我的 不知道需要的連接數。

我們可以在遞歸CTE中輕鬆做到這一點嗎?

declare @t table (
childID int, 
ParentID int, 
level int 
) 

insert into @t 
select 71, 154, 4 
union 
select 154, 192, 3 
union 
select 192, 209, 2 
union 
select 209, 0, 1 

select * from @t 

select t1.childID, t4.ChildID 
from @t t1 
inner join 
@t t2 
on t1.ParentID = t2.childID 
inner join 
@t t3 
on t2.ParentID = t3.childID 
inner join 
@t t4 
on t3.ParentID = t4.childID 
and t1.childID = 71 

- 我試着用遞歸CTE

-- I need to get 71, 209 but getting 209, 0 


    ;with MyCTE as 
    (
    select childID, ParentID from @t t1 
    where t1.level = 1 
    UNION ALL 
    select m.childID, t2.childID from @t t2 
    inner join 
    MyCTE m 
    on m.childID = t2.ParentID 
    ) 
select top 1 * from MyCTE 

回答

2

試試這個:

declare @t table (
childID int, 
ParentID int, 
level int 
) 

insert into @t 
select 71, 154, 4 
union 
select 154, 192, 3 
union 
select 192, 209, 2 
union 
select 209, 0, 1 

Declare @SearchChild int 
set @SearchChild=71 

    ;with MyCTE as (
     select t1.childID, t1.ParentID , @SearchChild AS searchChild, t1.level 
     from @t t1 
     where t1.childID = @SearchChild 
     UNION ALL 
     select t1.childID, t1.ParentID , c.SearchChild, t1.level 
     from @t t1 
     inner join MyCTE c on t1.childID=c.ParentID 
) 
select top 1 * from MyCTE order by level asc 

OUTPUT:

childID  ParentID searchChild level 
----------- ----------- ----------- ----------- 
209   0   71   1 

我不確定你在做什麼之後,沒有一行有209和71在一起?這是你能做的最好的事情。而且,這個CTE可以在鏈條上運行而不會失效,並且應該在大型桌面上運行得更好。

0

這是爲了做到這一點:

;with MyCTE as 
(
    select childID, ParentID, t1.childID As firstChild, 0 As depth 
    from @t t1 
    where t1.level = 1 

    UNION ALL 

    select t2.childID, t2.ParentID, m.firstChild, m.depth + 1 
    from @t t2 
    inner join MyCTE m 
    on m.childID = t2.ParentID 
) 
select TOP 1 childID, firstChild 
from MyCTE 
ORDER BY depth DESC 

給你

childId firstChild 
71  209 
+0

如果在表中,這是我認爲最有可能不止一個鏈將無法正常工作。 –

+0

@KM。它看起來像它的鏈接列表設置爲 – Magnus

+0

,測試數據是單鏈的,但是我將包含很多實際的表數據。從1級開始,你需要處理所有的鏈條,以找到'71'孩子。然而,如果你從'71'孩子開始並向後回到第一級,就像我在回答中一樣,你會發現它更快,並且多個連鎖不會影響結果。 –