### 分层数据的反向树遍历

``````SELECT RPAD ('*', 2 * LEVEL, '*') || ename ename, empno
FROM scott.emp
CONNECT BY PRIOR empno = mgr
``````

#### 1 个答案:

``````with e1 (ename, empno, lvl)
as ( select ename
, empno
, 0 as lvl
from emp
where mgr is null
union all
select  e2.ename
, e2.empno
, e1.lvl + 1
from emp e2, e1
where e2.mgr = e1.empno )
search depth first by empno set empno_order
select rpad ('*', 2 * e1.lvl, '*') || e1.ename ename
, e1.empno
from e1
order by empno_order
;
``````

`search depth first`子句保证结果集在显示兄弟节点之前显示给定节点的所有子节点。 （`search breadth first`将列出所有兄弟姐妹然后从层次结构的下一级开始。）

``````with e1 (ename, mgr, lvl)
as ( select e.ename
, e.mgr
, 0 as lvl
from emp e
where not exists ( select null
from emp x
where x.mgr = e.empno)
union all
select  e2.ename
, e2.mgr
, e1.lvl + 1
from emp e2, e1
where e2.empno = e1.mgr )
search depth first by mgr set mgr_order
select rpad ('*', 2 * e1.lvl, '*') || e1.ename ename
, e1.mgr
from e1
order by mgr_order
;
``````

``````ENAME                                 MGR
------------------------------ ----------
ALLEN                                7698
**BLAKE                              7839
****KING
JAMES                                7698
**BLAKE                              7839
****KING
MARTIN                               7698
**BLAKE                              7839
****KING
TURNER                               7698
...
``````