with as --工作备忘2016/1/13

来源:互联网 发布:怎么对比两列数据 编辑:程序博客网 时间:2024/05/22 10:34



1、With  <alias_name> as  <select...from > 

说明: 如SQL语句当中插入子查询(长篇),可在开头处为子查询起别名,在SQL主语句中直接使用

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),
   …

1
2
3
4
5
6
7
8
9
--相当于建了个e临时表
with eas (select *from scott.emp e where e.empno=7499)
select *from e;
 
--相当于建了e、d临时表
with
     eas (select *from scott.emp),
     das (select *from scott.dept)
select *from e, d where e.deptno = d.deptno;

其实就是把一大堆重复用到的sql语句放在with as里面,取一个别名,后面的查询就可以用它,这样对于大批量的sql语句起到一个优化的作用,而且清楚明了。

向一张表插入数据的with as用法

1
2
3
4
5
insert into table2
with
    s1as (select rownum c1 from dualconnect by rownum <= 10),
    s2as (select rownum c2 from dualconnect 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短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。


0 0
原创粉丝点击