在层次表中获取孩子的根父级 [英] Get Root parent of child in Hierarchical table

查看:39
本文介绍了在层次表中获取孩子的根父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含分层数据的表,结构如下:

I have a table with hierarchical data in it, the structure goes like this:

ID      ParentId
----   ----------
1       NULL
2       1
3       2
4       2
5       3
6       5

如果我传递节点 ID,我想通过在 SQL 中遍历其所有父节点来获取最高节点 ID/详细信息.

If I pass the node Id I would like to get the top most node Id/details by traversing through all its parents in SQL.

我尝试了 CTE,但我无法正确组合.然而,我把它作为一个函数工作,但它太慢了,我不得不发布这个问题.

I tried CTE, i somehow cannot get the combination correct. However, i got this working as a function but it is so slow that i had to post this question.

在上面的示例中,如果我通过 6,我希望获得最高的值,即 1.通过遍历 6 => 5 => 3 => 2 => [1](结果)

In the above example if I pass 6, i would want to have the top most i.e. 1. By traversing through 6 => 5 => 3 => 2 => [1] (result)

提前感谢您的帮助.

推荐答案

请尝试:

declare @id int=6
;WITH parent AS
(
    SELECT id, parentId  from tbl WHERE id = @id
    UNION ALL 
    SELECT t.id, t.parentId FROM parent
    INNER JOIN tbl t ON t.id =  parent.parentid
)

SELECT TOP 1 id FROM  parent
order by id asc

这篇关于在层次表中获取孩子的根父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆