---
title: "[转]集合操作UNION、UNION ALL、INTERSECT、MINUS区别"
author: "krs"
date: "2016-06-12T16:42:07Z"
tags: []
categories: ["数据库"]
slug: "union-union-all-intersect-minus"
draft: false
lastmod: "2016-06-12T16:42:07Z"
id: 2304482
url: "https://krs.iteye.com/blog/2304482"
---

有两个表job\_history表有10条数据;employees表有107条数据，这两个表有2条数据是重复的

SQL&gt; ed

已写入 file afiedt.buf

  1  SELECT employee\_id id, job\_id

  2  FROM   employees

  3  minus

  4  SELECT employee\_id id, job\_id

  5* FROM   job\_history

SQL&gt; /

表示返回在employees中存在，而不在job\_history中的记录，返回105条数据，去掉了2条重复的数据

SQL&gt; ed

已写入 file afiedt.buf

  1  SELECT employee\_id id, job\_id

  2  FROM   job\_history

  3  minus

  4  SELECT employee\_id id, job\_id

  5* FROM   employees

SQL&gt; /

表示返回在job\_history中存在，而不在employees中的记录，返回8条数据，去掉了2条重复的数据

 

 

 

集合操作中的ORDER BY子句

 

只能在整个集合的最后出现.可以按照第一个SELECT语句中的列名, 别名或者位置号排序.

SQL&gt; ed

已写入 file afiedt.buf

  1  SELECT employee\_id id, job\_id

  2  FROM   employees

  3  UNION all

  4  SELECT employee\_id, job\_id

  5  FROM   job\_history

  6* order by employee\_id

SQL&gt; /

 

下面的语句是正确的

SQL&gt; ed

已写入 file afiedt.buf

  1  SELECT employee\_id, job\_id

  2  FROM   employees

  3  UNION all

  4  SELECT employee\_id id, job\_id

  5  FROM   job\_history

  6* order by employee\_id

SQL&gt; /

 

 

 

小结

 

在SELECT 列表中的表达是必须有同样的数目和类型.

在结果中显示第一个Select语句中的列名.

除了 UNION ALL操作外,其他的集合操作都自动去掉重复值.

 

所以其他操作会隐式的进行排序操作(sql语句中并没有order by),使用CPU资源.

除了UNION ALL操作外，其他集合操作的输出结果默认按照升序的次序排列 .

 

所以其他操作会隐式的进行排序操作(sql语句中并没有order by),使用CPU资源.

 

（转自：[http://www.cnblogs.com/simplefrog/archive/2012/07/15/2592380.html](http://www.cnblogs.com/simplefrog/archive/2012/07/15/2592380.html)）