眾所周知的幾個結果集集合操作命令,今天詳細地測試了一下,發現一些問題,記錄備考。
假設我們有一個表Student,包括以下欄位與資料:
drop table student;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);commit;
Union和Union All的區別。
select *from studentwhere id < 4unionselect *from studentwhere id > 2 and id < 6
結果將是
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的區別之一在於對重複結果的處理。
接下來我們將兩個子查詢的順序調整一下,改為
--Unionselect *from studentwhere id > 2 and id < 6unionselect *from studentwhere id < 4
看看執行結果是否和你期望的一致?
--Union Allselect *from studentwhere id > 2 and id < 6union allselect *from studentwhere id < 4
那麼這個呢?
據此我們可知,區別之二在於對排序的處理。Union All將按照關聯的次序組織資料,而Union將進行依據一定規則進行排序。那麼這個規則是?我們換個查詢方式看看:
select score,id,namefrom studentwhere id > 2 and id < 6unionselect score,id,namefrom studentwhere 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,namefrom studentwhere id > 2unionselect score,id,namefrom studentwhere 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,namefrom studentwhere id > 2 and id < 7unionselect score,id,namefrom studentwhere id < 4unionselect score,id,namefrom studentwhere id > 8order by id desc
order by子句必須寫在最後一個結果集裡,並且其定序將改變操作後的排序結果。對於Union、Union All、Intersect、Minus都有效。
注意:
1,Union 可以對欄位名不同但資料類型相同的結果集進行合并;
2,如果欄位名不同的結果集進行Union,那麼對此欄位的Order by子句將失效。
=============================================================================
Intersect和Minus的操作和Union基本一致,這裡一起總結一下:
Union,對兩個結果集進行並集操作,不包括重複行,同時進行預設規則的排序;
Union All,對兩個結果集進行並集操作,包括重複行,不進行排序;
Intersect,對兩個結果集進行交集操作,不包括重複行,同時進行預設規則的排序;
Minus,對兩個結果集進行差操作,不包括重複行,同時進行預設規則的排序。
可以在最後一個結果集中指定Order by子句改變排序方式。
博文來源:http://www.cnblogs.com/RobertLee/archive/2008/03/05/898115.html