T-SQL get root node in hierarchy(T-SQL 获取层次结构中的根节点)
问题描述
所以我有两个这样结构的表:
So I have two tables structured like so:
CREATE TABLE #nodes(node int NOT NULL);
ALTER TABLE #nodes ADD CONSTRAINT PK_nodes PRIMARY KEY CLUSTERED (node);
CREATE TABLE #arcs(child_node int NOT NULL, parent_node int NOT NULL);
ALTER TABLE #arcs ADD CONSTRAINT PK_arcs PRIMARY KEY CLUSTERED (child_node, parent_node);
INSERT INTO #nodes(node)
VALUES (1), (2), (3), (4), (5), (6), (7);
INSERT INTO #arcs(child_node, parent_node)
VALUES (2, 3), (3, 4), (2, 6), (6, 7);
如果我有两个节点,比如说 1 和 2.我想要一个它们的根节点的列表.在这种情况下,它将是 1、4 和 7.我如何编写查询来获取该信息?
If I have two nodes, lets say 1 and 2. I want a list of their root nodes. In this case it would be 1, 4, and 7. How can I write a query to get me that information ?
我尝试编写它,但遇到了一个问题,即由于某种未知原因,我无法在 CTE 的递归部分使用 LEFT 连接.如果允许我执行 LEFT JOIN,这里是可行的查询.
I took a stab at writing it but ran into the issue that I can't use a LEFT join in the recursive part of a CTE for some unknown reason. Here is the query that would work if I was allowed to do a LEFT JOIN.
WITH root_nodes
AS (
-- Grab all the leaf nodes I care about and their parent
SELECT n.node as child_node, a.parent_node
FROM #nodes n
LEFT JOIN #arcs a
ON n.node = a.child_node
WHERE n.node IN (1, 2)
UNION ALL
-- Grab all the parent nodes
SELECT rn.parent_node as child_node, a.parent_node
FROM root_nodes rn
LEFT JOIN #arcs a -- <-- LEFT JOINS are Illegal for some reason :(
ON rn.parent_node = a.child_node
WHERE rn.parent_node IS NOT NULL
)
SELECT DISTINCT rn.child_node as root_node
FROM root_nodes rn
WHERE rn.parent_node IS NULL
有什么方法可以重组查询以获得我想要的?我无法重组数据,我真的希望远离临时表或不得不做任何昂贵的事情.
Is there a way I can restructure the query to get what I want ? I can't restructure the data and I would really prefer to stay away from temporary tables or having to do anything expensive.
谢谢,劳尔
推荐答案
将 LEFT JOIN 移出 CTE 怎么样?
How about moving the LEFT JOIN out of the CTE?
WITH root_nodes
AS (
-- Grab all the leaf nodes I care about
SELECT NULL as child_node, n.node as parent_node
FROM #nodes n
WHERE n.node IN (1, 2)
UNION ALL
-- Grab all the parent nodes
SELECT rn.parent_node as child_node, a.parent_node
FROM root_nodes rn
JOIN #arcs a
ON rn.parent_node = a.child_node
)
SELECT DISTINCT rn.parent_node AS root_node
FROM root_nodes rn
LEFT JOIN #arcs a
ON rn.parent_node = a.child_node
WHERE a.parent_node IS NULL
结果集为 1、4、7.
The result set is 1, 4, 7.
这篇关于T-SQL 获取层次结构中的根节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:T-SQL 获取层次结构中的根节点
基础教程推荐
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01