WITH AS,也叫子查詢部分(subquery factoring),可以定義一個SQL片斷,該SQL片斷會被整個SQL語句用到。可以使SQL語句的可讀性更高,也可以在UNION ALL的不同部分,作為提供數據的部分。
對於UNION ALL,使用WITH AS定義了一個UNION ALL語句,當該片斷被調用2次以上,優化器會自動將該WITH AS短語所獲取的數據放入一個Temp表中。而提示meterialize則是強制將WITH AS短語的數據放入一個全局臨時表中。很多查詢通過該方式都可以提高速度。
/*with as的簡單使用*/ with table1(id,mc,time) as (select top 7 egpuser_id,egpuser_mc,egp_modify_time from T_EGP_USER order by egp_modify_time asc) select * from table1;/*with as 后面的sqsl必須使用table1,否則報錯*/
WITH AS的優點:
(1). SQL可讀性增強。比如對於特定with子查詢取個有意義的名字等。
(2)、with子查詢只執行一次,將結果存儲在用戶臨時表空間中,可以引用多次,增強性能。
with egpDepCte(levelNo, egpdep_id) as /*with as:公用表表達式,可以理解為創建臨時表,僅供后面的sql語句使用。*/ ( select 0 levelNo, egpdep_id from t_egp_dep where egpdep_lx = '1' and egpdep_id = '3' union all/*Union All:對兩個結果集進行並集操作,包括重復行,不進行排序;*/ select (a.levelNo+1) levelNo, b.egpdep_id from egpDepCte a, t_egp_dep b where a.egpdep_id = b.egpdep_pid and b.egpdep_lx = '1' and (a.levelNo+1) < 4 ) select a.* from t_egp_dep a, egpDepCte b where a.egpdep_pid = b.egpdep_id and a.egpdep_lx = '0' and a.egpdep_relation_id in (52,58,154) order by b.levelNo, a.egp_order
