2014-09-19 87 views
0

我需要檢索孩子父母的最後(或第一)ID。簡單遞歸查詢最後父母的子女

實施例:

ID  PARENT_ID 
---------------- 
1  NULL 
2  1 
3  2 

所以,如果我搜索ID = 3的父ID我將具有1作爲結果。

我試過,但它給了我同樣的ID ...

with 
    tree(id) 
as 
(
    select id 
    from myTable 
    where id = 3 
    union all 
    select t.id 
    from myable t 
    inner join tree on tree.id = w.father_id 
) 
select * 
from tree; 

我已經看到的例子在這裏和在幾個網站;)

回答

1

你有一些不一致的命名在這裏。但無論如何,你的CTE也需要包含parent_id

像這樣:

with 
    tree(id,parent_id) 
as 
(
    select id, parent_id 
    from myTable 
    where id = 3 
    union all 
    select t.id, t.parent_id 
    from myTable t 
    inner join tree on t.id = tree.parent_id 
) 
select * 
from tree; 
+0

好的謝謝你,它的工作原理! 剛剛更改了'樹'參數和第二個選擇參數o t.father_id – Kaymaz 2014-09-19 12:11:32