分层查询返回最后一行

时间:2011-01-03 20:39:38

标签: sql oracle hierarchical-data

我有一个不会返回预期行的分层查询(员工徽章= 444)。

表:hr_data

badge fname supervisor_badge
111   Jeff  222
222   Joe   333
333   John  444
444   Tom   444

SQL:

SELECT CONNECT_BY_ISCYCLE As IC, 
       badge, 
       fname, 
       supervisor_badge
  FROM hr_data 
START WITH badge = '111' 
CONNECT BY NOCYCLE badge = PRIOR supervisor_badge 

返回的内容:

IC badge fname supervisor_badge
0 111   Jeff  222
0 222   Joe   333
1 333   John  444

预期结果:

IC badge fname supervisor_badge
0 111   Jeff  222
0 222   Joe   333
**0** 333   John  444
**1** 444   Tom   444

如何让此查询返回员工Tom然后停止?

2 个答案:

答案 0 :(得分:0)

从查询中删除NOCYCLE子句:

SELECT CONNECT_BY_ISCYCLE As IC, 
       badge, 
       fname, 
       supervisor_badge
  FROM hr_data 
START WITH badge = '111' 
CONNECT BY badge = PRIOR supervisor_badge 

答案 1 :(得分:0)

采用相反的方法并降序树可以获得所需的结果,但还没有让你的方法工作。这是相反的:

SELECT CONNECT_BY_ISCYCLE As IC, 
       badge, 
       fname, 
       supervisor_badge
  FROM (select '111' badge, 'Jeff' fname, '222' supervisor_badge from dual union all
        select '222' badge, 'Joe' fname, '333' supervisor_badge from dual union all
        select '333' badge, 'John' fname, '444' supervisor_badge from dual union all
        select '444' badge, 'Tom' fname, '444' supervisor_badge from dual
       ) 
START WITH badge = '444' 
CONNECT BY NOCYCLE PRIOR badge = supervisor_badge;

产地:

 IC BADGE FNAME      SUPERVISOR_BADGE
--- ----- ---------- ------------------
  1 444   Tom        444
  0 333   John       444
  0 222   Joe        333
  0 111   Jeff       222