Mysql联合查询UNION、UNION ALL

联合查询

常常会碰到这样的场景,将表的数据按照必定的查询条件查询出来以后,将结果放到一块儿显示,这个时候,就须要用到union,和union all关键字来实现这样的功能,web

union和union all区别

  • union all 把结果集直接合并在一块儿
  • union 是把 union all后的结果进行一次distinct,去除重复的记录

语法:

select * from t1
union | union all
select * from t2
union | union all
select * from tn

以两个表来演示

雇员表emp

在这里插入图片描述

部门表dept

在这里插入图片描述

将emp和dept表中的部门编号的集合显示出来。

select deptno from emp
union all
select deptno from dept;

在这里插入图片描述

将结果使用union去重显示

select deptno from emp
union
select deptno from dept;

在这里插入图片描述