union 和union all的区别

union和union all都可以将2个或多个表进行合并,但这些子查询必须具有相同的列,且对应的字段的类型必须一致。union all直接合并,取到表中的所有值,没有去重功能;union具有去重功能,取到的每个值都是唯一的。union all是将两个结果简单的合并后返回,union是按照字段的顺序排序后返回,所以从执行效率上union all要比union快。

对于两张表A、B,分别有两个字段id和name。

A
id 	name
1	Lily
2	Anna
3	Zhangxiao
B
id	name
1	Lily
3	Zhangxiao
4	Zhaoyao

使用union合并

select id, name from A
union
select id, name from B

查询结果


使用union all合并

select id, name from A
union all
select id, name from B

查询结果



猜你喜欢

转载自blog.csdn.net/qq_38332574/article/details/80410298