【问题标题】:Simple Recursive Query child to last parent简单递归查询子到最后一个父
【发布时间】:2014-09-19 11:58:22
【问题描述】:

我需要检索孩子父母的最后一个(或第一个)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 myTable t
   inner join tree on tree.id = t.father_id
)
select *
from tree;

我已经在这里和几个网站上看到了例子;)

【问题讨论】:

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


    【解决方案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;
    

    【讨论】:

    • 好的,谢谢,它有效!刚刚更改了“树”参数和第二个选择参数 o t.father_id