關於oracle中With函數的用法

先來一個例子:一列轉多行,直接出查詢SQL步驟。sql

(PS:一行轉多列就不寫了,listagg,wm_concat等能夠簡單實現)性能

(1)優化

SELECT 'AG,YH,PO,LS,GJ' A1, '1' A2 FROM DUAL
UNION ALL
SELECT 'A1G,Y1H,P1O,L1S,G1J,G3G' A1, '2' A2 FROM DUAL
;blog

查詢結果:it

(2)io

 

SELECT A2,
',' || A1 || ',' A1,
LENGTH(A1 || ',') - NVL(LENGTH(REPLACE(A1 || ',', ',')), 0) A3
FROM (SELECT 'AG,YH,PO,LS,GJ' A1, '1' A2
FROM DUAL
UNION ALL
SELECT 'A1G,Y1H,P1O,L1S,G1J,G3G' A1, '2' A2 FROM DUAL)
;table

查詢結果:test

(3)select

WITH TEMP0 AS
(SELECT LEVEL LV FROM DUAL CONNECT BY LEVEL <= 100)sql語句

SELECT A2,
SUBSTR(A1,
INSTR(A1, ',', 1, LV) + 1,
INSTR(A1, ',', 1, LV + 1) - INSTR(A1, ',', 1, LV) - 1) A1
FROM (SELECT A2,
',' || A1 || ',' A1,
LENGTH(A1 || ',') - NVL(LENGTH(REPLACE(A1 || ',', ',')), 0) A3
FROM (SELECT 'AG,YH,PO,LS,GJ' A1, '1' A2
FROM DUAL
UNION ALL
SELECT 'A1G,Y1H,P1O,L1S,G1J,G3G' A1, '2' A2 FROM DUAL)) B
JOIN TEMP0 C
ON C.LV <= B.A3
ORDER BY 1
;

查詢結果:

 

 

with as語法
–針對一個別名
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...;

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短語裏的數據放入一個全局臨時表裏。不少查詢經過這種方法均可以提升速度。

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 sql1union allselect * from sql2union allselect '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的易讀性,若是構造了多個子查詢,結構會更清晰;更重要的是:「一次分析,屢次使用」,這也是爲何會提供性能的地方,達到了「少讀」的目標

相關文章
相關標籤/搜索