1. 程式人生 > >oracle 樹形查詢

oracle 樹形查詢

--1.1 簡單的樹形查詢 SELECT empno AS 員工編碼,        ename AS 姓名,        mgr   AS 主管,        (PRIOR ename) AS 主管姓名   FROM emp   START WITH empno=7566   cONNECT BY (PRIOR empno) = mgr;

--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;

--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;

--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;