2014-09-10 43 views
0

從這裏跟進:Getting lowest level in a tree from any higher level with a self-join拼合分級表

我意識到,我其實是問錯了問題。我有一個分級表看起來是這樣的:

Type | Code | Parent_Type | Parent_Code 
    4 | 123 |  2  |  1 
    4 | 234 |  2  |  1 
    6 | 1234 |  4  |  123 
    6 | 2345 |  4  |  234 
    7 | 12345 |  6  |  1234 
    7 | 23456 |  6  |  1234 
    7 | 34567 |  6  |  2345 

它映射「2型」代碼「式4」,「4型」向「6類」和「類型6」至「7型」 。前面的問題(和答案)處理了如何選擇任何單個父代碼下的所有類型7代碼。因此,例如,如何獲得類型2下代碼爲1的所有類型7代碼。

但我實際上需要做的是將此表與類型和代碼列表結合在一起。因此,例如,我可能有一個表:

Type | Code 
    4 | 123 
    6 | 7851 

什麼,我需要做的就是那些代碼下的所有7級代碼。換句話說,(我想)我需要層次扁平化弄成這個樣子:

Type | Code | Parent_Type | Parent_Code 
    7 | 12345 |  2  |  7 
    7 | 23456 |  2  |  7 
    7 | 34567 |  2  |  7 
    7 | 12345 |  4  |  123 
    7 | 23456 |  4  |  123 
    7 | 34567 |  4  |  234 
    7 | 12345 |  7  |  12345  // Note: these last three might not 
    7 | 23456 |  7  |  23456  // be strictly needed 
    7 | 34567 |  7  |  34567 

於是我可以這樣做:

select p.type, p.code from myOtherTable o join mytable p on o.type = p.parent_type 
and o.code = p.parent_code 

要嘗試和扁平原始表,我已經嘗試了一些關於我原來的問題的答案,但沒有真正的運氣。例如:

with cte 
as (
select p.type, p.code, p.parent_type, p.parent_code 
from mytable as p 
where parent_type = 2 

union all 

select c.type, c.code, c.parent_type, c.parent_code 
from mytable as c 
inner join cte on c.parent_code = cte.code 
) 
select * 
from cte 

沒有任何用處不是搞糟表的排序其他,如果我只是直接調用:

select * from mytable 

回答

1

聽起來像一個遞歸CTE應該做的伎倆:

WITH cteTree As 
(
    SELECT 
    T.Type, 
    T.Code, 
    T.Parent_Type, 
    T.Parent_Code 
    FROM 
    RecordsToFind As F 
    INNER JOIN Tree As T 
    ON T.Type = F.Type 
    And T.Code = F.Code 

    UNION ALL 

    SELECT 
    T.Type, 
    T.Code, 
    T.Parent_Type, 
    T.Parent_Code 
    FROM 
    cteTree As F 
    INNER JOIN Tree As T 
    ON T.Parent_Type = F.Type 
    And T.Parent_Code = F.Code 
    WHERE 
    F.Type != 7 
) 
SELECT 
    Type, 
    Code, 
    Parent_Type, 
    Parent_Code 
FROM 
    cteTree 
WHERE 
    Type = 7 
; 

http://sqlfiddle.com/#!3/cc4ee/9

+0

謝謝,但是這並不能產生所需的輸出。它只返回兩行,不包括我需要能夠與另一個表連接的'parent_type'和'parent_code'。 – 2014-09-11 12:58:45

+0

@MattBurland:它只返回兩條記錄,因爲你正在搜索的記錄(6/7851)中的一條記錄在樣本數據中不存在,所以它只能找到4/123的後代。添加'parent_type'和'parent_code'列是微不足道的。 – 2014-09-11 15:37:33

+0

哦,等等,我很抱歉,我完全誤解了你發佈的內容。我沒有意識到你的小提琴已經加入了它。 – 2014-09-11 15:49:16