查询集合运算
关键字: 并集: union, 全并集: union all, 交集: intersect, 差集: minus
比如说有集合 A ( 1 , 2 , 3 ) , B ( 2 , 3 , 4 ):
A∪B(取并集) = ( 1, 2, 3, 4) ,如果是全并集就是 (1, 2, 3, 2, 3, 4)
A∩B (取交集) = ( 2, 3 )
A – B(取差集) = ( 1 ) ,B – A = (4)
1、并集
例:部门为10以及部门为20的员工信息的并集
select * from emp where deptno=10
union
select * from emp where deptno=20;
2、全并集
例如:部门号为10和10或20的员工信息的并集
select * from B where deptno=10
union all
select * from B where deptno in(10,20);
3、交集
例如:部门号为10和部门为10或20的员工信息的交集
select * from B where deptno=10
intersect
select * from B where deptno in(10,20);
4、差集
例如:部门号为10或30与部门号为10或20的员工信息的差集
select * from B where deptno in(10, 30)
minus
select * from B where deptno in(10,20);
注意
参与运算的各个集合必须列数相同,且类型一致
采用第一个集合作为最后的表头(如果要写别名也在第一个语句上写)
order by永远在最后
可以使用括号改变执行顺序
如果列数不一样使用to_char(null)或to_number(null)代替:
例如:
select deptno,sum(salary) from B group by deptno,job
union
select deptno,to_char(null),sum(sal) form B group by deptno;