oracle中的with的用法,oracle中with子句的用法(转)

语法:

WITH query_name AS (subquery)

[, query_name AS (subquery) ]...

使用在主select关键字前,oracle将其当做一个内联视图或者临时表使用。

例子:

1.最简单的使用方法:

如查询部门名称包含“A”的所有员工信息

--with clause

with a as

(select deptno from dept where dname like '%A%')

select * from emp where deptno in (select * from a);

with a as

(select deptno from dept where dname like '%A%'),--a结果集

a2 as(select * from a where deptno>20)--a1结果集直接从a中筛选

select * from emp where deptno in (select * from a2);

2.多层同级只能用一个with,并且后面的结果集可以使用前面的结果集:

查询部门名称包含“A”并且部门编号大于20的所有员工信息

with a as

(select deptno from dept where dname like '%A%'),--a结果集

a2 as(select * from a where deptno>20)--a1结果集直接从a中筛选

select * from emp where deptno in (select * from a2);

3.不同级查询可以使用多个with:

查询部门名称包含“A”并且部门编号大于20的所有员工信息的另外一种实现方式如下

with a as

(select deptno from dept where dname like '%A%')--a结果集

select * from emp where deptno in (--括号内层作为子查询,为第二级

with a2 as(select * from a where deptno>20)--a1结果集直接从a中筛选

select * from a2

);

使用场景:

那什么情况下能使用到with子句呢?以下我就举几个简单的例子,简单的说明以下:

1.我想测试一句sql,而我不想专门建立一个测试表:

我想测试成绩大于90的学生,我不想建立学生表,可以用到with子句

with stu as(

select '张娜' sname,99 score from dual union

select '王杰' ,35 from dual union

select '宋丽' ,85 from dual union

select '陈晓' ,73 from dual union

select '李元' ,100 from dual

)--with 组成一个临时的结果集,存放在用户的临时表空间

select * from stu where score>90

2.         当一个sql重复用到某个相同的结果集作为子查询:

--查询销售部工资>1500或者销售部工资小于1000的员工

select * from emp where deptno=(select deptno from dept where dname ='SALES') and sal >1500

union all

select * from emp where deptno=(select deptno from dept where dname ='SALES') and sal <1000

--以上sql select deptno from dept where dname ='SALES'需要执行两次,影响效率

--可以使用with优化一下

with salno as(select deptno from dept where dname ='SALES')

select * from emp where deptno=(select * from salno) and sal >1500

union all

select * from emp where deptno=(select * from salno) and sal <1000

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值