博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Union、Union All、Intersect、Minus
阅读量:4658 次
发布时间:2019-06-09

本文共 1497 字,大约阅读时间需要 4 分钟。

 

转自:http://www.2cto.com/database/201208/148795.html

 

Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;

Union All:对两个结果集进行并集操作,包括重复行,不进行排序;
Intersect:对两个结果集进行交集操作,不包括重复行,同时进行默认规则的排序;
Minus:对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序。
  www.2cto.com  
具体讲讲Union和Union All。先来看一个例子:
 
有一张学生表student如下:
id
name score
1
Aaron 78
2
Bill 76
3
Cindy 89
4
Damon 90
5
Ella 73
6
Frado 61
7
Gill 99
8
Hellen 56
9
Ivan 93
10
Jay 90
 
看看以下4段SQL语句
[sql] 
1)  
select * from student where id<4  
union  
select * from student where 2<id and id<6  
  
2)  
select * from student where 2<id and id<6  
union  
select * from student where id<4  
    www.2cto.com  
3)  
select * from student where id<4  
union all  
select * from student where 2<id and id<6  
  
4)  
select * from student where 2<id and id<6  
union all  
select * from student where id<4  
 
看看4段SQL语句的执行结果:
id
name score
1
Aaron 78
2
Bill 76
3
Cindy 89
4
Damon 90
5
Ella 73
同上
  www.2cto.com  
id
name score
1
Aaron 78
2
Bill 76
3
Cindy 89
3
Cindy 89
4
Damon 90
5
Ella 73
id
name score
3
Cindy 89
4
Damon 90
5
Ella 73
1
Aaron 78
2
Bill 76
3
Cindy 89
从以上四个结果来看,可以得出结论:Union是不可重复的,有序的。Union All是可以重复的,无序的。
 
那么Union的自动排序的默认规则是什么呢?
众多周知,以上的select *就相当于select id, name, score。默认排序规则是按照select之后的第一个字段排序,也就是id。如果想要按照score排序,可以这样写:select score, id, name。
那么可不可以用order by排序呢,答案是:可以。不过order by一定要写到最后一个结果集里,如下面SQL语句:
 
[sql] 
select * from student where 2<id and id<6  
union    www.2cto.com  
select * from student where id<4  
order by score  
order by 排序对于Union、Union All、Intersect、Minus都有效。

转载于:https://www.cnblogs.com/bluedeblog/p/6653946.html

你可能感兴趣的文章
欧拉函数模板
查看>>
寒武纪C++日常实习生面经(其他人面试题)
查看>>
ECShop后台管理菜单显示、隐藏、修改、增加
查看>>
ubuntu18(笔记本) faster-rcnn实例程序运行
查看>>
dos其他
查看>>
elisp 错误提示
查看>>
Git使用及关联远程仓库
查看>>
STC-51开发板-单片机控制数码管&按键&点阵综合操作
查看>>
区块链采集
查看>>
工厂模式
查看>>
codeforces 983A Finite or not?判断进制有限表示
查看>>
linux常用命令
查看>>
转:过滤器Filter配置总结
查看>>
python学习——读取染色体长度(七:读取fasta文件)
查看>>
java学习——集合框架(泛型,Map)
查看>>
MATLAB之画确定区域内互不接触的球
查看>>
CSE 421/521 – Operating Systems
查看>>
ref 游标(动态游标)
查看>>
CentOS虚拟机网卡配置
查看>>
Ubuntu配置pyethapp
查看>>