简单递归查询子项到最后一个父项

时间:2014-09-19 11:58:22

标签: sql sql-server parent-child recursive-query

我需要检索孩子父母的最后一个(或第一个)id。

示例:

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

因此,如果我搜索id = 3的父ID,我将得到1。

我尝试了这个,但它给了我相同的身份......

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 个答案:

答案 0 :(得分: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;
相关问题