SQL语句——10、集合操作

时间:2021-12-18 04:35:07

用于多条select语句合并结果

  • union 并集 去重
  • union all 并集 不去重
  • intersect 交集
  • minus 差集

union

A集合和B集合的合并,但去掉两集合重复的部分,会排序

select deptno,ename from emp where deptno in (20,30)
 union
select deptno,ename from emp where deptno in (20,10);

DEPTNO ENAME
---------- ----------
10 CLARK
10 KING
10 MILLER
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD

 

union all

A集合和B集合的合并,不去重,不排序

select deptno,ename from emp where deptno in (20,30)
 union all
select deptno,ename from emp where deptno in (20,10);


DEPTNO ENAME
---------- ----------
20 SMITH
30 ALLEN
30 WARD
20 JONES
30 MARTIN
30 BLAKE
20 SCOTT
30 TURNER
20 ADAMS
30 JAMES
20 FORD
20 SMITH
20 JONES
10 CLARK
20 SCOTT
10 KING
20 ADAMS
20 FORD
10 MILLER

19 rows selected.

intersect

两个集合的交集部分,排序并去重

select deptno,ename from emp where deptno in (20,30)
 intersect
select deptno,ename from emp where deptno in (20,10);

DEPTNO ENAME
---------- ----------
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH

minus

取两个集合的差集,A集合中存在,B集合中不存在的数据(取A集合中B集合不存在的数据),去重

select deptno,ename from emp where deptno in (20,30)
 minus
select deptno,ename from emp where deptno in (20,10);

DEPTNO ENAME
---------- ----------
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD

6 rows selected.