Get Root parent of child in Hierarchical table(在层次表中获取孩子的根父级)
问题描述
我有一个包含分层数据的表,结构如下:
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
这篇关于在层次表中获取孩子的根父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在层次表中获取孩子的根父级


基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01