在oracle中查找层次结构中的最后一个子节点

时间:2014-03-12 02:09:17

标签: sql oracle oracle10g hierarchical-query

我有一张像

这样的表格
prnt_id   child_id
-----------------
1           2
2           4
3
5
6           7
7           8
8           9

我的结果应该包含

prnt_id  child_id
-----------------
1          4
3
5
6          9

我正在使用oracle 10g。

我尝试使用connect by但没有得到预期的结果。

1 个答案:

答案 0 :(得分:2)

使用CONNECT_BY_ROOT从根目录获取prnt_id,并使用CONNECT_BY_ISLEAF指示,无论这是叶子节点。这样的事情应该有效:

SELECT PRNT_ID, 
       CHILD_ID
FROM (SELECT CONNECT_BY_ROOT PRNT_ID PRNT_ID, CHILD_ID, CONNECT_BY_ISLEAF leaf 
      FROM TABLE
      CONNECT BY PRIOR CHILD_ID = PRNT_ID
      START WITH prnt_id NOT IN (SELECT CHILD_ID
                                 FROM TABLE
                                 WHERE CHILD_ID IS NOT NULL))
WHERE leaf = 1

例如,这将为您提供所需的结果:

WITH dat AS (SELECT 1 prnt_id, 2 child_id FROM DUAL
             UNION ALL
             SELECT 2 prnt_id, 4 child_id FROM DUAL
             UNION ALL
             SELECT 3 prnt_id, NULL child_id FROM DUAL
             UNION ALL
             SELECT 5 prnt_id, NULL child_id FROM DUAL
             UNION ALL
             SELECT 6 prnt_id, 7 child_id FROM DUAL
             UNION ALL
             SELECT 7 prnt_id, 8 child_id FROM DUAL
             UNION ALL             
             SELECT 8 prnt_id, 9 child_id FROM DUAL)
SELECT PRNT_ID, 
       CHILD_ID
FROM (SELECT CONNECT_BY_ROOT PRNT_ID PRNT_ID, CHILD_ID, CONNECT_BY_ISLEAF leaf FROM dat
      CONNECT BY PRIOR CHILD_ID = PRNT_ID
      START WITH prnt_id NOT IN (SELECT CHILD_ID
                                 FROM dat
                                 WHERE CHILD_ID IS NOT NULL))
WHERE leaf = 1


PRNT_ID CHILD_ID
1       4
3   
5   
6       9