Oracle多⾏、多列⼦查询
本⽂使⽤到的是oracle数据库scott⽅案所带的表,scott是oracle数据库⾃带的⽅案,使⽤前请确保其解锁
⼀、多⾏⼦查询
多⾏⼦查询⼦查询是嵌⼊在其他Sql语句中的select语句,Oracle⼦查询分为两种:⼀种是单⾏⼦查询,⼀种是多⾏⼦查询
1、单⾏⼦查询
单⾏⼦查询的select语句只返回⼀⾏数据,也就是说嵌⼊在其他Sql语句中的那个select查询值返回⼀⾏数据。
例:查询emp表中,与Smith同⼀部门的所有员⼯
select*from emp where deptno=
(select deptno from emp where ENAME='SMITH');--这⾥的select查询只返回⼀⾏数据
所以,我们把⼦查询的嵌⼊的select语句⾄返回⼀⾏数据的这类⼦查询,称为单⾏⼦查询
2、多⾏⼦查询
了解了单⾏⼦查询的原理,那么多⾏⼦查询⾃然⽽然的就知道了,多⾏⼦查询就是嵌⼊在其他Sql语句中的select查询返回多⾏数据
例:查询所有员⼯中⼯作和部门10的⼯作⼀样的员⼯信息
select*from emp where job in
(select distinct job from emp where deptno=10) --这⾥的select查询返回多⾏记录
注意左图红框中的关键字只能⽤in,不能使⽤'=','='号表⽰⼀对⼀,in表⽰处于⼀个范围(⽤来处理⼦查询返回多⾏记录),如果这⾥使⽤'='号,也就是执⾏如下语句:
select*from emp where job =
(select distinct job from emp where deptno=10) --这⾥的select查询返回多⾏记录oracle数据库怎么查询表
3、多⾏⼦查询中的特殊操作符
虽然in能解决多⾏⼦查询中的=的问题,但是如果要和⼦查询的结果集中的字段⽐较⼤⼩呢?显然⽤in是不够⽤的ok,下⾯即将使⽤的操作符,就是来解决这个问题的.
3.1、多⾏⼦查询中的all操作符
例:查询⽐部门30所有员⼯的⼯资都要⾼度员⼯信息
select*from emp where sal>
(select sal from emp where deptno=30) --这⾥的select查询返回多⾏记录
执⾏sql之后发现和=是⼀样的问题,因为'>'表⽰⼀对⼀的关系,⽽⼦查询返回多个结果集,所以报错了,那怎么办呢?总不可能⽤in吧!这⾥就要使⽤all了,如下代码:
select*from emp where sal>
all (select sal from emp where deptno=30) --这⾥的select查询返回多⾏记录
在⼦查询前⾯加上all关键字,表⽰当检索emp表时,只检索出哪些⽐(⼦查询结果集中最⼤的还要⼤)的数据⾏
所以上⾯的代码也可以这样表⽰:
select*from emp where sal>
(select max(sal) from emp where deptno=30)
3.2、多⾏⼦查询中的any操作符
在了解了all操作符之后,any操作符也就好理解了。
select*from emp where sal>
any (select sal from emp where deptno=30) --这⾥的select查询返回多⾏记录
这段代码表⽰:检索出emp表,只检索那些(只要⽐⼦查询的结果集的任意⼀⾏⼤)就⾏的数据⾏,所以上⾯的代码也相当于:
select*from emp where sal>
(select min(sal) from emp where deptno=30) --这⾥的select查询返回多⾏记录
⼆、多列⼦查询
例1:查询与smith部门和岗位完全相同的员⼯
1、⾸先使⽤多⾏⼦查询来解决这个问题
select*from emp where deptno=
(select deptno from emp where ename='SMITH')
and job=
(select job from emp where ename='SMITH')
2、使⽤多列⼦查询来解决这个问题
select*from emp where (deptno,job)=(select deptno,job from emp where ename='SMITH') --列的顺序⼀定要相同
加⼊换了列的顺序,代码如下:
select*from emp where (job,deptno)=(select deptno,job from emp where ename='SMITH') --列的顺序⼀定要相同
例2:查询⾼于⾃⼰部门平均⼯资的员⼯信息
select*from emp a,(select deptno,ceil(avg(sal)) as avgsal from emp group by deptno) b
where a.deptno=b.deptno and a.sal>b.avgsal
解决思路:通过分组函数求出各个部门的平均薪⽔,然后将平均薪⽔通过deptno和emp进⾏连表查询,然后⽐较薪⽔和平均值,得出结果集。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论