with as语法
–针对一个别名
with tmp as (select * from tb_name)php
–针对多个别名
with
tmp as (select * from tb_name),
tmp2 as (select * from tb_name2),
tmp3 as (select * from tb_name3),
…html
1
2
3
4
5
6
7
8
9
|
--至关于建了个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语句起到一个优化的做用,并且清楚明了。sql
向一张表插入数据的with as用法性能
1
2
3
4
5
|
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短语里的数据放入一个全局临时表里。不少查询经过这种方法均可以提升速度。spa
1
2
3
4
5
6
7
8
9
10
|
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);
|
with as优势
增长了sql的易读性,若是构造了多个子查询,结构会更清晰;
更重要的是:“一次分析,屡次使用”,这也是为何会提供性能的地方,达到了“少读”的目标code