我有一张像
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 但没有得到预期的结果。
我有一张像
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 但没有得到预期的结果。
使用 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