oracle 树形查询

--1.1 简单的树形查询
SELECT empno AS 员工编码,
       ename AS 姓名,
       mgr   AS 主管,
       (PRIOR ename) AS 主管姓名
  FROM emp
  START WITH empno=7566
  cONNECT BY (PRIOR empno) = mgr;

oracle 树形查询_第1张图片

--1.2 根节点,分支节点,叶节点

level:返回所在的等级;

connect_by_isleaf:如果当前节点下没有其他节点返回1,其他返回0。
SELECT LPAD('-',(LEVEL-1)*2,' -')|| empno AS 员工编码,
       ename AS 姓名,
       mgr   AS 主管编码,
       LEVEL AS 级别,
       DECODE(LEVEL,1,1) AS 根节点,
       DECODE(connect_by_isleaf,1,1) AS 叶子节点,
       CASE WHEN (connect_by_isleaf=0 AND LEVEL>1) THEN 1 END AS 分支节点
  FROM emp
 START WITH empno=7566
 CONNECT BY (PRIOR empno)=mgr;

oracle 树形查询_第2张图片

--1.3 sys_connect_by_path 

sys_connect_by_path :为了方便的显示其路径
SELECT empno AS 员工编码,
       ename AS 姓名,
       mgr   AS 主管,
       sys_connect_by_path(ename,' , ') AS enames
 FROM emp
 START WITH empno=7566
 CONNECT BY (PRIOR empno) = mgr;

oracle 树形查询_第3张图片

--1.4 树形查询中的排序
SELECT LPAD('-',(LEVEL-1)*2,' -')|| empno AS 员工编码,
       ename AS 姓名,
       mgr   AS 主管编码
  FROM emp
 START WITH empno=7566
 CONNECT BY (PRIOR empno) = mgr
 ORDER SIBLINGS BY empno DESC; 

oracle 树形查询_第4张图片

 

你可能感兴趣的:(oracle)