转自: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都有效。

最新文章

  1. mac系统安装node
  2. mysql 学习碎片
  3. 面试整理之DOM事件阶段
  4. swift学习网站
  5. UVa 11134 (区间上的贪心) Fabled Rooks
  6. linux使用mount挂载iso文件
  7. Robotium源码分析之Instrumentation进阶
  8. Webstrom 常用操作记录
  9. VB6之GIF分解
  10. Shell编程(2)
  11. @Autowired注解与@resource注解的区别(十分详细)
  12. 阿里云服务器晚上运行定时任务报Too many connections
  13. Linux内核剖析(四)为arm内核构建源码树
  14. 【JUC源码解析】CompletableFuture
  15. Zabbix监控系统部署:配置详解
  16. Java 清理和垃圾回收
  17. Java 多条件复杂排序小结
  18. bat批处理设置静态、动态、ping、查看网络配置
  19. pgpool-II 的使用
  20. iKcamp|基于Koa2搭建Node.js实战(含视频)☞ 规范与部署

热门文章

  1. EasyUI treegrid 删除一条或多条记录
  2. 多个else if语句
  3. Mysql Cluster节点类型(转载)
  4. 线程之 CPthon中的GIL与Lock的分析与解决办法
  5. 【合】C#线程
  6. SVN revert命令的使用
  7. Flask之视图(二)
  8. postman 中url有动态变换的值时,可以按下面方式变换。
  9. 怎么分辨linux是红帽还是Centos系统
  10. 神奇的make自动生成include file的功能