Oracle中with as的用法详解

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

与UNION ALL结合使用

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语句的优点:

(1). SQL可读性增强。比如对于特定with子查询取个有意义的名字等。

(2)、with子查询只执行一次,将结果存储在用户临时表空间中,可以引用多次,增强性能。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值