例如,如果我有以下特定数据表:
Table X
Node_ID ParentNode_ID
---- ----
1 -
2 1
3 1
4 2
5 2
6 4
7 5
8 6
9 8
我需要一个查询来选择节点'2'的子节点和大孩子(和盛大的孩子......),这意味着以下结果:
children_of_node2
------
4
5
6
7
8
9
如何使用select查询和不使用函数或在oracle SQL中声明变量?
答案 0 :(得分:2)
这只是对Gordon Linoff的评论的详细阐述 以下是一些例子 首先创建表和测试数据:
CREATE TABLE X (
NODE_ID NUMBER,
PARENTNODE_ID NUMBER
);
INSERT INTO X VALUES (1, NULL);
INSERT INTO X VALUES (2, 1);
INSERT INTO X VALUES (3, 1);
INSERT INTO X VALUES (4, 2);
INSERT INTO X VALUES (5, 2);
INSERT INTO X VALUES (6, 4);
INSERT INTO X VALUES (7, 5);
INSERT INTO X VALUES (8, 6);
INSERT INTO X VALUES (9, 8);
然后是第一个例子,来自CONNECT BY
:
为节点2创建查询:
SELECT
NODE_ID,
(LEVEL -1) AS DISTANCE_FROM_ANCESTOR
FROM X
WHERE LEVEL > 1
CONNECT BY PRIOR NODE_ID = PARENTNODE_ID
START WITH NODE_ID = 2
ORDER BY 2 ASC, 1 ASC;
测试一下:
NODE_ID DISTANCE_FROM_ANCESTOR
4 1
5 1
6 2
7 2
8 3
9 4
第二个例子,通过递归CTE:
创建查询:
WITH RECURSION_CTE(NODE_ID, DISTANCE_FROM_ANCESTOR)
AS
(SELECT
NODE_ID,
0 AS DISTANCE_FROM_ANCESTOR
FROM X
WHERE NODE_ID = 2
UNION ALL
SELECT
X.NODE_ID,
RECURSION_CTE.DISTANCE_FROM_ANCESTOR + 1 AS DISTANCE_FROM_ANCESTOR
FROM X
INNER JOIN RECURSION_CTE ON X.PARENTNODE_ID = RECURSION_CTE.NODE_ID
)
SELECT
NODE_ID,
DISTANCE_FROM_ANCESTOR
FROM RECURSION_CTE
WHERE DISTANCE_FROM_ANCESTOR > 0
ORDER BY 2 ASC, 1 ASC;
测试一下:
NODE_ID DISTANCE_FROM_ANCESTOR
4 1
5 1
6 2
7 2
8 3
9 4