ORACLE递归
发布网友
发布时间:2022-12-12 00:00
我来回答
共1个回答
热心网友
时间:2023-11-28 20:13
about connect by
SELECT empno, ename, job, mgr, deptno, LEVEL, sys_connect_by_path(ename,'\'), connect_by_root(ename) FROM emp START WITH mgr IS NULL CONNECT BY mgr = PRIOR empno
WITH T(empno, ename, job, mgr, deptno, the_level, path,top_manager) AS ( ---- 必须把结构写出来
SELECT empno, ename, job, mgr, deptno ---- 先写锚点查询,用START WITH的条件
,1 AS the_level ---- 递归起点,第一层
,'\'||ename ---- 路径的第一截
,ename AS top_manager ---- 原来的CONNECT_BY_ROOT
FROM scott.EMP
WHERE mgr IS NULL ---- 原来的START WITH条件
UNION ALL ---- 下面是递归部分
SELECT e.empno, e.ename, e.job, e.mgr, e.deptno ---- 要加入的新一层数据,来自要遍历的emp表
,1 + t.the_level ---- 递归层次,在原来的基础上加1。这相当于CONNECT BY查询中的LEVEL伪列
,t.path||'\'||e.ename ---- 把新的一截路径拼上去
,t.top_manager ---- 直接继承原来的数据,因为每个路径的根节点只有一个
FROM t, scott.emp e ---- 典型写法,把子查询本身和要遍历的表作一个连接
WHERE t.empno = e.mgr ---- 原来的CONNECT BY条件
) ---- WITH定义结束
SELECT * FROM T
EMPNO ENAME JOB MGR DEPTNO THE_LEVEL PATH TOP_MANAGER
----- ---------- --------- ----- ------ ---------- -------------------------------------------------------------------------------- -----------
7839 KING PRESIDENT 10 1 \KING KING
7566 JONES MANAGER 7839 20 2 \KING\JONES KING
7698 BLAKE MANAGER 7839 30 2 \KING\BLAKE KING
7782 CLARK MANAGER 7839 10 2 \KING\CLARK KING
7999 MIKE ANALYST 7566 30 3 \KING\JONES\MIKE KING
7499 ALLEN SALESMAN 7698 30 3 \KING\BLAKE\ALLEN KING
7521 WARD SALESMAN 7698 30 3 \KING\BLAKE\WARD KING
7654 MARTIN SALESMAN 7698 30 3 \KING\BLAKE\MARTIN KING
7788 SCOTT ANALYST 7566 20 3 \KING\JONES\SCOTT KING
7844 TURNER SALESMAN 7698 30 3 \KING\BLAKE\TURNER KING
7900 JAMES CLERK 7698 30 3 \KING\BLAKE\JAMES KING
7902 FORD ANALYST 7566 20 3 \KING\JONES\FORD KING
7934 MILLER CLERK 7782 10 3 \KING\CLARK\MILLER KING
7369 SMITH CLERK 7902 20 4 \KING\JONES\FORD\SMITH KING
7876 ADAMS CLERK 7788 20 4 \KING\JONES\SCOTT\ADAMS KING