1. 程式人生 > >Oracle學習筆記:with as子查詢用法

Oracle學習筆記:with as子查詢用法

  With as短語,也叫做子查詢部分(subquery factoring),可以定義一個SQL片斷,該SQL片斷會被整個SQL語句用到。該語句會在真正的查詢之前預先構造一個臨時表,之後可以多次使用做進一步的分析和處理。

  優勢:

  1.可以使SQL語句的可讀性更高;
  2.一次分析,多次使用,提高效能;

  語法:

with
    tempName
as
    (select ...)
select * from tempName;
with
    tmp as (select * from table_1),
    tmp2 as (select *
from table_2), tmp3 as (select * from table_3) ...

  實際上就是把重複用到是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相當於虛擬檢視。


 END 2018-12-03 10:27:02