Oracle的子查询和集合运算

子查询:
子查询解决了不能一步求解的问题
子查询要包含在括号内。
将子查询放在比较条件的右侧。
单行操作符对应单行子查询,多行操作符对应多行子查询。
可以在主查询的where 、select、 having 、from后面放置子查询
不可以在group by后面放置子查询
主查询和子查询可以不是同一张表,只要子查询返回的结果主查询可以使用
一般不在子查询中使用order by
一般先执行子查询 再执行主查询;但相关子查询除外
单行子查询只能使用单行操作符 多行子查询只能使用多行操作符

理论上,多表查询的性能要高于子查询,建议尽量使用多表查询。

select *
from emp
where sal > (select sal
              from emp
               where ename='SCOTT');

select ename,sal,(select job from emp where empno=7839) 一列
from emp;

select *
from (select ename,sal from emp);

 select *
 from emp
 where deptno=(select deptno
               from dept
              where dname='SALES');

select *
from emp
where deptno in (select deptno from dept where dname='SALES' or dname='ACCOUNTING');

select *
from emp
where sal > any (select sal from emp where deptno=30);

select *
from emp
where sal > all (select sal from emp where deptno=30);

select *
from emp
where empno not in (select mgr from emp);

select *
from emp
where empno not in (select mgr from emp where mgr is not null);


集合运算
UNION/UNION ALL 并集
INTERSECT 交集
MINUS 差集

UNION运算符返回两个集合去掉重复元素后的所有记录
UNION ALL 返回两个集合的所有记录,包括重复的

INTERSECT 运算符返回同时属于两个集合的记录

MINUS返回属于第一个集合,但不属于第二个集合的记录

集合运算的注意事项:
select语句中参数类型和个数要一致。
可以使用括号改变集合执行的顺序
如果有order by子句,必须放到每一句查询语句后
集合运算采用第一个语句的表头作为表头

select deptno,job,sum(sal) from emp group by deptno,job
union
select deptno,to_char(null),sum(sal) from emp group by deptno
union
select to_number(null),to_char(null),sum(sal) from emp;


select ename,sal from emp
where sal between 700 and 1300
INTERSECT
select ename,sal from emp
where sal between 1201 and 1400;

select ename,sal from emp
where sal between 700 and 1300
minus
select ename,sal from emp
where sal between 1201 and 1400;

Coding Diary

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值