Oracle中的Union、Union All、Intersect、Minus

衆所周知的幾個結果集集合操做命令,今天詳細地測試了一下,發現一些問題,記錄備考。web

假設咱們有一個表Student,包括如下字段與數據:測試

drop table student;orm

create table student
(
id int primary key,
name nvarchar2(50) not null,
score number not null
);排序

insert into student values(1,'Aaron',78);
insert into student values(2,'Bill',76);
insert into student values(3,'Cindy',89);
insert into student values(4,'Damon',90);
insert into student values(5,'Ella',73);
insert into student values(6,'Frado',61);
insert into student values(7,'Gill',99);
insert into student values(8,'Hellen',56);
insert into student values(9,'Ivan',93);
insert into student values(10,'Jay',90);it

commit;io

  • Union和Union All的區別。table

select *
from student
where id < 4select

unionwebkit

select *
from student
where id > 2 and id < 6nio

結果將是

1    Aaron    78
2    Bill    76
3    Cindy    89
4    Damon    90
5    Ella    73

若是換成Union All鏈接兩個結果集,則返回結果是:

1    Aaron    78
2    Bill    76
3    Cindy    89
3    Cindy    89
4    Damon    90
5    Ella    73

能夠看到,Union和Union All的區別之一在於對重複結果的處理。

接下來咱們將兩個子查詢的順序調整一下,改成

--Union

select *
from student
where id > 2 and id < 6

union

select *
from student
where id < 4

看看執行結果是否和你指望的一致?

--Union All

select *
from student
where id > 2 and id < 6

union all

select *
from student
where id < 4

那麼這個呢?

據此咱們可知,區別之二在於對排序的處理。Union All將按照關聯的次序組織數據,而Union將進行依據必定規則進行排序。那麼這個規則是?咱們換個查詢方式看看:

select score,id,name
from student
where id > 2 and id < 6

union

select score,id,name
from student
where id < 4

結果以下:

73    5    Ella
76    2    Bill
78    1    Aaron
89    3    Cindy
90    4    Damon

和咱們預料的一致:將會按照字段的順序進行排序。以前咱們的查詢是基於id,name,score的字段順序,那麼結果集將按照id優先進行排序;而如今新的字段順序也改變了查詢結果的排序。而且,是按照給定字段a,b,c...的順序進行的order by。即結果是order by a,b,c...........的。咱們看下一個查詢:

select score,id,name
from student
where id > 2

union

select score,id,name
from student
where id < 4

結果以下:

56    8    Hellen
61    6    Frado
73    5    Ella
76    2    Bill
78    1    Aaron
89    3    Cindy
90    4    Damon
90    10    Jay
93    9    Ivan
99    7    Gill

能夠看到,對於score相同的記錄,將按照下一個字段id進行排序。若是咱們想自行控制排序,是否是用order by指定就能夠了呢?答案是確定的,不過在寫法上有須要注意的地方:

select score,id,name
from student
where id > 2 and id < 7

union

select score,id,name
from student
where id < 4

union

select score,id,name
from student
where id > 8
order by id desc

order by子句必須寫在最後一個結果集裏,而且其排序規則將改變操做後的排序結果。對於Union、Union All、Intersect、Minus都有效。

=================================================================================================================

Intersect和Minus的操做和Union基本一致,這裏一塊兒總結一下:

Union,對兩個結果集進行並集操做,不包括重複行,同時進行默認規則的排序;

Union All,對兩個結果集進行並集操做,包括重複行不進行排序

Intersect,對兩個結果集進行交集操做,不包括重複行,同時進行默認規則的排序;

Minus,對兩個結果集進行差操做,不包括重複行,同時進行默認規則的排序。

能夠在最後一個結果集中指定Order by子句改變排序方式。

相關文章
相關標籤/搜索