簡單的樹形查詢--prior放在select中使用
簡單的樹形查詢
使用scott使用者下的表:emp
想要查出上級主管的姓名(sql1):
select e.empno as "員工編碼",
e.ename as "員工姓名",
e.mgr as "主管編碼",
"主管姓名" as "主管姓名"
from emp e
start with e.empno = 7566
connect by (prior e.empno) = e.mgr
order by 1;
查詢之後主管姓名要如何展示出來呢,想想可以再關聯一次emp查出姓名程式碼入戲(sql2):
看看執行計劃:select e.empno as "員工編碼", e.ename as "員工姓名", e.mgr as "主管編碼", b.ename as "主管姓名" from emp e left join emp b on e.mgr = b.empno start with e.empno = 7566 connect by (prior e.empno) = e.mgr order by 1;
Plan Hash Value : 1231760462
--------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost | Time |
--------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 14 | 560 | 8 | 00:00:01 |
| 1 | SORT ORDER BY | | 14 | 560 | 8 | 00:00:01 |
| * 2 | CONNECT BY NO FILTERING WITH START-WITH | | | | | |
| * 3 | HASH JOIN OUTER | | 14 | 336 | 7 | 00:00:01 |
| 4 | TABLE ACCESS FULL | EMP | 14 | 196 | 3 | 00:00:01 |
| 5 | TABLE ACCESS FULL | EMP | 14 | 140 | 3 | 00:00:01 |
--------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
------------------------------------------
* 2 - access("E"."MGR"=PRIOR "E"."EMPNO")
* 2 - filter("E"."EMPNO"=7566)
* 3 - access("E"."MGR"="B"."EMPNO"(+))
有個更簡單的方法查出主管的姓名(sql3):
select e.empno as "員工編碼",
e.ename as "員工姓名",
e.mgr as "主管編碼",
prior e.ename as "主管姓名"
from emp e
start with e.empno = 7566
connect by (prior e.empno) = e.mgr
order by 1;
檢視執行計劃:
Plan Hash Value : 2173065311
--------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost | Time |
--------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 14 | 462 | 4 | 00:00:01 |
| 1 | SORT ORDER BY | | 14 | 462 | 4 | 00:00:01 |
| * 2 | CONNECT BY NO FILTERING WITH START-WITH | | | | | |
| 3 | TABLE ACCESS FULL | EMP | 14 | 196 | 3 | 00:00:01 |
--------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
------------------------------------------
* 2 - access("E"."MGR"=PRIOR "E"."EMPNO")
* 2 - filter("E"."EMPNO"=7566)
是不是快了很多。
總結:之前一直認為prior 只用在 connect by 後面,沒想到也可以用在select 裡。
如果沒有oracle環境執行sql,可以試試下面的地址: