总结一下两者使用上的区别:
union all只是合并查询结果,并不会进行去重和排序操作,在没有去重的前提下,使用union all的执行效率要比union高
- 查询结果集取并集时是否包含重复数据
union: 对两个结果集进行并集操作, 不包括重复行,相当于distinct, 同时进行默认规则的排序;
union all: 对两个结果集进行并集操作, 包括重复行, 即所有的结果全部显示, 不管是不是重复;
union看到结果中ID=3的只有一条
select * from student2 where id < 4
union
select * from student2 where id > 2 and id < 6
union all 结果中ID=3的结果有两个
select * from student2 where id < 4
union all
select * from student2 where id > 2 and id < 6
- 获取结果集之后的操作
union: 会对获取的结果进行排序操作
union all: 不会对获取的结果进行排序操作
注意:
- union和union all都是对于两个或多个select语句的结果集
- 使用union或union all要注意两个表必须有相同的数量的列,同时列也必须有相同或相似的数据类型
- 每条select语句中的列的顺序也是必须相同的
- union得到的是没有重复的记录,union all得到的是记录条数是两张表中记录的条数之和