如何使用SQL在数据库中查找树类结构中的最后一级子节点

时间:2017-01-24 14:52:07

标签: sql oracle hierarchical-data recursive-query

我将父子关系存储在表

如果我用1查询,我想要检索所有LAST LEVEL 1的孩子。 我应该回来5,6,8。

忽略随附的任何周期性数据。

请参阅附件图片enter image description here

1 个答案:

答案 0 :(得分:3)

使用分层查询并使用pseudocolumns CONNECT_BY_ISLEAFCONNECT_BY_ISCYCLE将输出限制为仅非循环叶子行:

Oracle安装程序

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;

<强>查询

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

<强>输出

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