ITPub博客

首页 > 数据库 > Oracle > sql 中的with 语句使用

sql 中的with 语句使用

Oracle 作者:hd_system 时间:2016-11-24 10:54:40 0 删除 编辑

一直以来都很少使用sql中的with语句,但是看到了一篇文章中关于with的使用,它的确蛮好用,希望以后记得使用这个语句。
一、with 的用法
With alias_name as (select1)[,alias_namen as (select n) ]--中括号可以省略
Select ….
举例,如下两表:
A B
ID NAME ID NAME
1 LI 1 LI
2 QIN 3 SUN
语句如下:
例1
with test_with as(select * from A) select * from B where B.id in(select id from test_with)
----------------------------------------------------------------------------------------------------------------------------
with a as (select * from dept) select * from emp where emp.deptno in (select deptno from a)

例2
with test_with1 as(select * from A),test_with2 as(select * from B)
select * from B where B.id in(select id from test_with1)
union all
select * from test_with2

----------------------------------------------------------------------------------------------------------------------------
with a as(select * from dept),b as(select * from emp)
select * from B where B.deptno in(select deptno from a)
union all
select * from b

二、with的相关总结
1.使用with子句可以让子查询重用相同的with查询块,通过select调用(with子句只能被select查询块引用),一般在with查询用到多次情况下。在引用的select语句之前定义,同级只能定义with关键字只能使用一次,多个用逗号分割。

2.with子句的返回结果存到用户的临时表空间中,只做一次查询,反复使用,提高效率。

3.在同级select前有多个查询定义的时候,第1个用with,后面的不用with,并且用逗号隔开。

4.最后一个with 子句与下面的查询之间不能有逗号,只通过右括号分割,with 子句的查询必须用括号括起来

5.如果定义了with子句,而在查询中不使用,那么会报ora-32035 错误:未引用在with子句中定义的查询名。(至少一个with查询的name未被引用,解决方法是移除未被引用的with查询),注意:只要后面有引用的就可以,不一定非要在主查询中引用,比如后面的with查询也引用了,也是可以的。

6.前面的with子句定义的查询在后面的with子句中可以使用。但是一个with子句内部不能嵌套with子句。

7.当一个查询块名字和一个表名或其他的对象相同时,解析器从内向外搜索,优先使用子查询块名字。

8.with查询的结果列有别名,引用的时候必须使用别名或*。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29209863/viewspace-2128986/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2016-10-12

  • 博文量
    149
  • 访问量
    99038