關於oracle with as用法

2021-07-11 17:35:17 字數 3852 閱讀 6295

with as

語法

–針對乙個別名

with tmp as (select * from tb_name)

–針對多個別名

with

tmp as (select * from tb_name),

tmp2 as (select * from tb_name2),

t*** as (select * from tb_name3),…1

2

3

4

5

6

7

8

9

--相當於建了個e臨時表

witheas(select*fromscott.emp ewheree.empno=7499)

select*frome;

--相當於建了e、d臨時表

with

eas(select*fromscott.emp),

das(select*fromscott.dept)

select*frome, dwheree.deptno = d.deptno;

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

向一張表插入資料的with as用法

1

2

3

4

5

insertintotable2

with

s1as(selectrownum c1fromdualconnectbyrownum <= 10),

s2as(selectrownum c2fromdualconnectbyrownum <= 10)

selecta.c1, b.c2froms1 a, s2 bwhere...;

select s1.sid, s2.sid from s1 ,s2需要有關聯條件,不然結果會是笛卡爾積。

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短語裡的資料放入乙個全域性臨時表裡。很多查詢通過這種方法都可以提高速度。

1

2

3

4

5

6

7

8

9

10

with

sql1as(selectto_char(a) s_namefromtest_tempa),

sql2as(selectto_char(b) s_namefromtest_tempbwherenotexists (selects_namefromsql1whererownum=1))

select*fromsql1

unionall

select*fromsql2

unionall

select'no records'fromdual

wherenotexists (selects_namefromsql1whererownum=1)

andnotexists (selects_namefromsql2whererownum=1);

with as優點

增加了sql的易讀性,如果構造了多個子查詢,結構會更清晰;

更重要的是:「一次分析,多次使用」,這也是為什麼會提供效能的地方,達到了「少讀」的目標

關於oracle with as用法

with as 語法 針對乙個別名 with tmp as select from tb name 針對多個別名 with tmp as select from tb name tmp2 as select from tb name2 t as select from tb name3 1 2 3 ...

關於oracle with as用法

with as 語法 針對乙個別名 with tmp as select from tb name 針對多個別名 with tmp as select from tb name tmp2 as select from tb name2 t as select from tb name3 1 2 3 ...

關於oracle with as用法

with as 語法 針對乙個別名 with tmp as select from tb name 針對多個別名 with tmp as select from tb name tmp2 as select from tb name2 t as select from tb name3 1 2 3 ...