数据库的Union、Union All、Intersect、Minus

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

Union All:对两个结果集进行并集操作,包括重复行,不进行排序;

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

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


具体讲讲Union和Union All。先来看一个例子:

有一张学生表student如下:

idnamescore
1Aaron78
2Bill76
3Cindy89
4Damon90
5Ella73
6Frado61
7Gill99
8Hellen56
9Ivan93
10Jay90

看看以下4段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

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语句的执行结果:

idnamescore
1Aaron78
2Bill76
3Cindy89
4Damon90
5Ella73

同上


idnamescore
1Aaron78
2Bill76
3Cindy89
3Cindy89
4Damon90
5Ella73


idnamescore
3Cindy89
4Damon90
5Ella73
1Aaron78
2Bill76
3Cindy89

从以上四个结果来看,可以得出结论:Union是不可重复的,有序的。Union All是可以重复的,无序的。

那么Union的自动排序的默认规则是什么呢?

众多周知,以上的select *就相当于select id, name, score。默认排序规则是按照select之后的第一个字段排序,也就是id。如果想要按照score排序,可以这样写:select score, id, name。

那么可不可以用order by排序呢,答案是:可以。不过order by一定要写到最后一个结果集里,如下面SQL语句:

select * from student where 2<id and id<6
union
select * from student where id<4
order by score

order by 排序对于Union、Union All、Intersect、Minus都有效。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值