以前一直不知道Union和Union All到底有什麼區別,今天來好好的研究一下,網上查到的結果是下面這個樣子,可是還是不是很理解,下面將自己親自驗證:
Union:對兩個結果集進行並集操作,不包括重複行,同時進行默認規則的排序;
Union All:對兩個結果集進行並集操作,包括重複行,不進行排序;
下面進行簡單的測試(因爲是測試,所以sql代碼寫的很簡單,沒有什麼很嚴格的規範,只是爲了理解這兩者之間的區別)
嚴格的標準寫法應該先判斷數據庫是否存在,表是否存在等等約束。
第一步,建庫:
Create database Test
go
use Test
go
第二步,建表:
Create table Table1
(
id int not null,
name varchar(20) not null
)
Create table Table2
(
id int not null,
name varchar(20) not null
)
第三步,插入測試數據:
Insert into Table1 values (1,'姚羽')
Insert into Table1 values (2,'邊兵兵')
Insert into Table1 values (3,'袁磊')
Insert into Table2 values (1,'姚羽')
Insert into Table2 values (2,'柳春平')
Insert into Table2 values (3,'張永超')
Insert into Table2 values (4,'劉華健')
第四步,測試開始:
select * from Table1
select * from Table2
執行兩個表的查詢結果如下
可以很容易的看到,上面插入的測試數據當中,有一條是重複的
那麼我們 先看執行union 看看
select * from Table1
union
select * from Table2
再執行union all 看看
select * from Table1
union all
select * from Table2
相信到此時,應該明白了union 和 union all 的區別了, 我以前也一直沒搞清楚,這次看視頻,就終於搞清楚了