简体   繁体   中英

how to find the last level child nodes in tree kind structure in database using SQL

I have a parent child relationship stored in a table

If I query with 1, I want to retrieve all the LAST LEVEL Children of 1. I should get back 5, 6,8.

Ignore any cyclical data that comes along.

Please see the attached image 在此处输入图片说明

Use a hierarchical query and restrict the output to only the non-cyclic leaf rows using the pseudocolumns CONNECT_BY_ISLEAF and CONNECT_BY_ISCYCLE :

Oracle Setup :

CREATE TABLE your_table ( parent_column, child_column ) AS
SELECT 1, 2 FROM DUAL UNION ALL
SELECT 2, 3 FROM DUAL UNION ALL
SELECT 3, 4 FROM DUAL UNION ALL
SELECT 4, 5 FROM DUAL UNION ALL
SELECT 3, 6 FROM DUAL UNION ALL
SELECT 3, 7 FROM DUAL UNION ALL
SELECT 7, 8 FROM DUAL;

Query :

SELECT child_column
FROM   your_table
WHERE  CONNECT_BY_ISLEAF  = 1
AND    CONNECT_BY_ISCYCLE = 0
START WITH parent_column = 1
CONNECT BY NOCYCLE PRIOR child_column = parent_column

Output :

CHILD_COLUMN
------------
           5
           6
           8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM