2014-09-19 64 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