ORACLE WITH AS 用法


With查詢語句不是以select開始的,而是以“WITH”關鍵字開頭
    可認為在真正進行查詢之前預先構造了一個臨時表,之后便可多次使用它做進一步的分析和處理

WITH Clause方法的優點
     增加了SQL的易讀性,如果構造了多個子查詢,結構會更清晰;更重要的是:“一次分析,多次使用”,這也是為什么會提供性能的地方,達到了“少讀”的目標。

     第一種使用子查詢的方法表被掃描了兩次,而使用WITH Clause方法,表僅被掃描一次。這樣可以大大的提高數據分析和查詢的效率。

     另外,觀察WITH Clause方法執行計划,其中“SYS_TEMP_XXXX”便是在運行過程中構造的中間統計結果臨時表。

 

語法:

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.deptno = d.deptno;

 

其實就是把一大堆重復用到的sql語句放在with as里面,取一個別名,后面的查詢就可以用它,這樣對於大批量的sql語句起到一個優化的作用,而且清楚明了。

向一張表插入數據的 with as 用法:

insert into table2
with
    s1 as (select rownum c1 from dual connect by rownum <= 10),
    s2 as (select rownum c2 from dual connect by rownum <= 10)
select a.c1, b.c2 from s1 a, s2 b where...;

with as 相當於虛擬視圖。

with as短語,也叫做子查詢部分(subquery factoring),可以讓你做很多事情,定義一個sql片斷,該sql片斷會被整個sql語句所用到。

有的時候,是為了讓sql語句的可讀性更高些,也有可能是在union all的不同部分,作為提供數據的部分。
  
特別對於union all比較有用。

因為union all的每個部分可能相同,但是如果每個部分都去執行一遍的話,則成本太高,所以可以使用with as短語,則只要執行一遍即可。

如果with as短語所定義的表名被調用兩次以上,則優化器會自動將with as短語所獲取的數據放入一個temp表里,如果只是被調用一次,則不會。

而提示materialize則是強制將with as短語里的數據放入一個全局臨時表里。

很多查詢通過這種方法都可以提高速度。

with
    sql1 as (select to_char(a) s_name from test_tempa),
    sql2 as (select to_char(b) s_name from test_tempb where not exists (select s_name from sql1 where rownum=1))
select * from sql1
union all
select * from sql2
union all
select 'no records' from dual
       where not exists (select s_name from sql1 where rownum=1)
       and not exists (select s_name from sql2 where rownum=1);

with as優點
增加了sql的易讀性,如果構造了多個子查詢,結構會更清晰;
更重要的是:“一次分析,多次使用”,這也是為什么會提供性能的地方,達到了“少讀”的目標

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM