问题
For instance if I have following table with this particular data:
Table X
Node_ID ParentNode_ID
---- ----
1 -
2 1
3 1
4 2
5 2
6 4
7 5
8 6
9 8
and I need a query to select children and grand children (and grand grand children...) of node '2', meaning following result:
children_of_node2
------
4
5
6
7
8
9
how can I do it with a select query and not using functions or declaring variables in oracle SQL?
回答1:
This is just an elaboration on Gordon Linoff's comment.
Here are some examples.
First create the table and test data:
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);
Then a first example, via CONNECT BY
:
Create the query for node 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;
And test it:
NODE_ID DISTANCE_FROM_ANCESTOR
4 1
5 1
6 2
7 2
8 3
9 4
A second example, via recursive CTE:
Create the query:
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;
And test it:
NODE_ID DISTANCE_FROM_ANCESTOR
4 1
5 1
6 2
7 2
8 3
9 4
来源:https://stackoverflow.com/questions/43440317/how-to-select-all-children-and-grand-children-of-a-node-in-sql-oracle