以前一直不知道Union和Union All到底有什么區別,今天來好好的研究一下,網上查到的結果是下面這個樣子,可是還是不是很理解,下面將自己親自驗證:
Union:對兩個結果集進行并集操作,不包括重復行,同時進行默認規則的排序;
Union All:對兩個結果集進行并集操作,包括重復行,不進行排序;
下面進行簡單的測試(因為是測試,所以sql代碼寫的很簡單,沒有什么很嚴格的規范,只是為了理解這兩者之間的區別)
嚴格的標準寫法應該先判斷數據庫是否存在,表是否存在等等約束
第一步,建庫:
view plainCreate database Test go use Test go
第二步,建表:
view plainCreate table Table1 ( id int not null, name varchar(20) not null ) Create table Table2 ( id int not null, name varchar(20) not null )
第三步,插入測試數據:
view plainInsert 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,‘劉華健’)
第四步,測試開始:
view plainselect * from Table1 select * from Table2
執行兩個表的查詢結果如下

可以很容易的看到,上面插入的測試數據當中,有一條是重復的
那么我們 先看執行union 看看
view plainselect * from Table1 union select * from Table2

再執行union all 看看
view plainselect * from Table1 union all select * from Table2

相信到此時,應該明白了union 和 union all 的區別了, 我以前也一直沒搞清楚,這次看視頻,就終于搞清楚了
新聞熱點
疑難解答