您的位置:首页 > 数据库 > Oracle

Oracle的子查询和集合运算

2017-06-17 17:47 435 查看
子查询:

子查询解决了不能一步求解的问题

子查询要包含在括号内。

将子查询放在比较条件的右侧。

单行操作符对应单行子查询,多行操作符对应多行子查询。

可以在主查询的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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle