union all和union的区别

union all和union的区别

union的默认排序规则见下文

数据库: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

如图:

union all和union的区别

1.2换下select执行顺序: 

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

结果如图:

union all和union的区别

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

 2.1执行union all

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

如图:

union all和union的区别

2.2换下select的顺序:

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

如图:

union all和union的区别

总结: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  
    ;

执行结果:

union all和union的区别

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

特别注意:如果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  

 

运行结果如下:

union all和union的区别

文章来自:union all和union的区别_麦子的博客-CSDN博客_unionall 

上一篇:多测师肖老师__单表建表和练习(1.8)


下一篇:SqlServer使用insert into一次插入多笔数据