sql - 获取根元素和所有后代 MS SQL
问题描述
我应该从该结构中获取所有后代的根元素:
rootA
rootB
child1
rootC
child2
chold3
rootD
child4
结果:
Root| Child
rootA child1
rootA child2
rootA child3
rootD child4
我明白,首先我应该在没有父母的情况下获得根元素:
SELECT DISTINCT
rootId,
childId
FROM
root
WHERE rootId IS NULL
但我不知道下一步。你有一些变种吗?
谢谢!
解决方案
这是通过公用表表达式 (CTE) 完成的:
;WITH cte_hierarchy AS (
-- get all roots
SELECT DISTINCT
rootId, childId
FROM
root
WHERE rootId IS NULL
UNION ALL
-- this is the recursive part
-- get all children for all roots, including children of children, etc.
SELECT
child.rootId, child.childId
FROM root child
JOIN cte_hierarchy parent ON parent.childid=child.rootid
)
SELECT * FROM cte_hierarchy;
推荐阅读
- ibm-midrange - RPGLE as400 中的小数问题
- javascript - 循环元素中的元素
- postgresql - Spring Boot JPA - 按复合唯一列查找
- c - 如果在一个表达式中同时使用左移和右移,为什么会有所不同?
- javascript - 在 Django 模板中运行 javascript 变量
- amazon-web-services - 我无法访问我刚刚在 aws 上创建的网站?
- c++ - 无法弄清楚为什么重载的 operator[] 没有被调用
- c - 如何从文件中提取数据以用作 C 中的变量
- python-3.x - 桌面应用程序不起作用,但命令中的脚本有效
- java - 两个数组的交集(索引越界异常)