原理
使用WITH AS其實是:爲了進行查詢之前預先構造了一個臨時表,之後便可多次使用它做進一步的分析和處理;
優點
1.增加了sql的易讀性,如果構造了多個子查詢,結構會更清晰;
更重要的是:“一次分析,多次使用”,這也是爲什麼會提供性能的地方,達到了“少讀”的目標;
2.增加了SQL的易讀性,如果構造了多個子查詢,結構會更清晰;更重要的是:“一次分析,多次使用”,這也是爲什麼會提供性能的地方,達到了“少讀”的目標。
3.第一種使用子查詢的方法表被掃描了兩次,而使用WITH Clause方法,表僅被掃描一次。這樣可以大大的提高數據分析和查詢的效率。另外,觀察WITH Clause方法執行計劃,其中“SYS_TEMP_XXXX”便是在運行過程中構造的中間統計結果臨時表。
4,with as短語,也叫做子查詢部分(subquery factoring),可以讓你做很多事情,定義一個sql片斷,該sql片斷會被整個sql語句所用到。
語法
with tempName as (select ....)
select ...
//針對一個別名
with tmp as (select * from tb_name)
//針對多個別名
with
tmp as (select * from tb_name),
tmp2 as (select * from tb_name2),
tmp3 as (select * from tb_name3),
…
--相當於建了個e臨時表
with e as (select * from scott.emp e where e.empno=7499)
select * from e;
//相當於建了e、d臨時表
with
e as (select * from scott.emp),
d as (select * from scott.dept)
select * from e, d where e.deptn