union:对多个结果集进行并集操作,不包括重复行,同时进行排序。
union all:对多个结果集进行并集操作,包括重复行,不进行排序。
查询部门小于30号的员工信息,和部门大于20小于40号的员工信息。
①.先查询部门小于30号的员工信息。
SELECT
employees_id
,last_name
,salary
,department_id
FROM employees
WHERE department_id < 30; “`
employees_id
,last_name
,salary
,department_id
FROM employees
WHERE department_id < 30; “`
查询部门大于20小于40的员工信息。
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40;“`
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40;“`
③.用union连接两张表
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id < 30
UNION
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40; “`
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id < 30
UNION
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40; “`
其结果默认排序并去重,两张表都有30号部门信息,结果只出现一次。
④.下面用union all连接两张表
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id < 30
UNION ALL
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40; “`
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id < 30
UNION ALL
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40; “`
其结果没有去重,也没有排序,排序结果对比下边结果,先去查询20到40的员工信息,在查小于30的员工信息。
⑤.对比查询结果
SELECT
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40
UNION ALL
SELECT
employees_id
,last_name
,salary
,department_id
FROM employees
WHERE department_id < 30;“`
employees_id
,last_name
,salary
,department_id
FROM
employees
WHERE
department_id BETWEEN 20 and 40
UNION ALL
SELECT
employees_id
,last_name
,salary
,department_id
FROM employees
WHERE department_id < 30;“`
默认是没有进行排序的。
到此这篇关于MySQL中union和unionall区别的文章就介绍到这了,更多相关MySQL union和unionall内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:简单了解MySQL union all与union的区别MySQL中union和join语句使用区别的辨析教程mysql中union和union?all的使用及注意事项MySQL如何使用union all获得并集排序浅析mysql union和union all5分钟了解MySQL5.7中union all用法的黑科技MySQL中使用or、in与union all在查询命令下的效率对比Mysql联合查询UNION和UNION ALL的使用介绍
© 版权声明
文章版权归作者所有,未经允许请勿转载。