ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

union all和union的区别

2021-12-22 12:02:45  阅读:186  来源: 互联网

标签:insert 区别 union into values test id select


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

如图:

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  

 

运行结果如下:

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

标签:insert,区别,union,into,values,test,id,select
来源: https://blog.csdn.net/mazhongjia/article/details/122081950

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有