sql 中的with 語句使用

hd_system發表於2016-11-24

一直以來都很少使用sql中的with語句,但是看到了一篇文章中關於with的使用,它的確蠻好用,希望以後記得使用這個語句。
一、with 的用法
With alias_name as (select1)[,alias_namen as (select n) ]--中括號可以省略
Select ….
舉例,如下兩表:
A B
ID NAME ID NAME
1 LI 1 LI
2 QIN 3 SUN
語句如下:
例1
with test_with as(select * from A) select * from B where B.id in(select id from test_with)
----------------------------------------------------------------------------------------------------------------------------
with a as (select * from dept) select * from emp where emp.deptno in (select deptno from a)

例2
with test_with1 as(select * from A),test_with2 as(select * from B)
select * from B where B.id in(select id from test_with1)
union all
select * from test_with2

----------------------------------------------------------------------------------------------------------------------------
with a as(select * from dept),b as(select * from emp)
select * from B where B.deptno in(select deptno from a)
union all
select * from b

二、with的相關總結
1.使用with子句可以讓子查詢重用相同的with查詢塊,透過select呼叫(with子句只能被select查詢塊引用),一般在with查詢用到多次情況下。在引用的select語句之前定義,同級只能定義with關鍵字只能使用一次,多個用逗號分割。

2.with子句的返回結果存到使用者的臨時表空間中,只做一次查詢,反覆使用,提高效率。

3.在同級select前有多個查詢定義的時候,第1個用with,後面的不用with,並且用逗號隔開。

4.最後一個with 子句與下面的查詢之間不能有逗號,只透過右括號分割,with 子句的查詢必須用括號括起來

5.如果定義了with子句,而在查詢中不使用,那麼會報ora-32035 錯誤:未引用在with子句中定義的查詢名。(至少一個with查詢的name未被引用,解決方法是移除未被引用的with查詢),注意:只要後面有引用的就可以,不一定非要在主查詢中引用,比如後面的with查詢也引用了,也是可以的。

6.前面的with子句定義的查詢在後面的with子句中可以使用。但是一個with子句內部不能巢狀with子句。

7.當一個查詢塊名字和一個表名或其他的物件相同時,解析器從內向外搜尋,優先使用子查詢塊名字。

8.with查詢的結果列有別名,引用的時候必須使用別名或*。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29209863/viewspace-2128986/,如需轉載,請註明出處,否則將追究法律責任。

相關文章