1. 程式人生 > >ORACLE WITH AS 用法

ORACLE WITH AS 用法

語法:

with tempName as (select ....)
select ...

例:現在要從1-19中得到11-14。一般的sql如下:

select * from
(
            --模擬生一個20行的資料
             SELECT LEVEL AS lv
               FROM DUAL
         CONNECT BY LEVEL < 20
) tt
WHERE tt.lv > 10 AND tt.lv < 15

使用With as 的SQL為:

with TT as(
                --模擬生一個20行的資料
SELECT LEVEL AS lv FROM DUAL CONNECT BY LEVEL < 20 ) select lv from TT WHERE lv > 10 AND lv < 15

With查詢語句不是以select開始的,而是以“WITH”關鍵字開頭

  • 可認為在真正進行查詢之前預先構造了一個臨時表,之後便可多次使用它做進一步的分析和處理

WITH Clause方法的優點

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

  • 第一種使用子查詢的方法表被掃描了兩次,而使用WITH Clause方法,表僅被掃描一次。這樣可以大大的提高資料分析和查詢的效率。
  • 另外,觀察WITH Clause方法執行計劃,其中“SYS_TEMP_XXXX”便是在執行過程中構造的中間統計結果臨時表。

語法:

--針對一個別名
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表裡,如果只是被呼叫一次,則不會。

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

Oracle WITH AS 用法

語法

with tempName1 as (select ....),tempName2 as (select ....)
select ...from  tempName 

例子

//普通使用方法
Select * from (
    select name ,age from stu
    union 
    select name,age from tech
    union)

//wtih as 
with schoolPeople as (
    select name ,age from stu
    union 
    select name,age from tech
    union)
select * from schoolPeople

注意事項

① 子查詢可重用相同或者前一個with查詢塊,通過select呼叫(with子句也只能被select呼叫) ② with子句的查詢輸出儲存到使用者臨時表空間,一次查詢,到處使用 ③ 同級select前有多個查詢定義,第一個用with,後面的不用with,並且用逗號分割 ④ 最後一個with查詢塊與下面的select呼叫之間不能用逗號分割,只通過右括號分離,with子句的查詢必須括號括起 ⑤如果定義了with子句,而在查詢中不使用,則會報ora-32035錯誤,只要後面有引用的即可,不一定在select呼叫,在後with查詢塊引用也是可以的 ⑥ 前面的with子句定義的查詢在後面的with子句中可以使用,但是一個with子句內部不能巢狀with子句 ⑦ with查詢的結果列有別名,引用時候必須使用別名或者*