union和union all的区别是,union会自动压缩多个结果集合中的重复结果,而union all则将所有的结果全部显示出来,不管是不是重复。
Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;
UNION在进行表链接后会筛选掉重复的记录,所以在表链接后会对所产生的结果集进行排序运算,删除重复的记录再返回结果。
实际大部分应用中是不会产生重复的记录,最常见的是过程表与历史表UNION


Union All:对两个结果集进行并集操作,包括重复行,不进行排序;
如果返回的两个结果集中有重复的数据,那么返回的结果集就会包含重复的数据了。

 

数据库:mysql

实例


create table test  
(  
id int primary key,  
name varchar(50) not null,  
score int not null  
); 
  
 
insert into test values(1,'Aaron',78);  
insert into test values(2,'Bill',76);  
insert into test values(3,'Cindy',89);  
insert into test values(4,'Damon',90);  
insert into test values(5,'Ella',73);  
insert into test values(6,'Frado',61);  
insert into test values(7,'Gill',99);  
insert into test values(8,'Hellen',56);  
insert into test values(9,'Ivan',93);  
insert into test values(10,'Jay',90); 

 

1.1执行union

 select *  
   from test  
    where id<4  
    union  
    select *  
    from student  
    where id>2 and id<6 

如图:

1.2换下select执行顺序:

    select *  
    from student  
    where id>2 and id<6
    union   
    select *  
    from test  
    where id<4  
 

结果如图:

总结:可以看到,对于UNION来说,交换两个SELECT语句的顺序后结果仍然是一样的,这是因为UNION会自动排序

 

2.1执行union all

 select *  
   from test  
    where id<4  
    union all
    select *  
    from student  
    where id>2 and id<6 

如图:

2.2换下select的顺序:

    select *  
    from student  
    where id>2 and id<6 
    union all
 select *  
   from test  
    where id<4  

如图:

总结:UNION ALL在交换了SELECT语句的顺序后结果则不相同,因为UNION ALL不会对结果自动进行排序。

 

那么这个自动排序的规则是什么呢?我们交换一下SELECT后面选择字段的顺序(前面使用SELECT *相当于SELECT ID,NAME,SCORE)

select score,id,name  
    from student  
    where id<4  
    union  
    select score,id,name  
    from student  
    where id>2 and id<6  
    ;  

执行结果:

可以看出,默认是根据主键升序排序

特别注意:如果id不是主键,会根据score字段排序;

unoin也可以自定义排序,指定某个字段升序或是降序,如下:

select score,id,name  
from test  
where id > 2 and id < 7  
  
union  
  
select score,id,name  
from test  
where id < 4  
  
union  
  
select score,id,name  
from test  
where id > 8  
order by score desc  

运行结果如下:

 

参考文章:
https://www.cnblogs.com/wcl2017/p/7078685.html
https://blog.csdn.net/wanghai__/article/details/4712555

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐