以前一直不知道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 的區別了, 我以前也一直沒搞清楚,這次看視頻,就終於搞清楚了
- 眾覽群雄,唯我杭城獨秀——一貼匯總杭州校區所有就業薪資
- http://bbs.itheima.com/forum.php?mod=viewthread&tid=345570
- [color=inherit !important]一貼看杭州分校吃住行,學習生活攻略大集錦
- http://bbs.itheima.com/thread-347847-1-1.html
- 全新圖文杭州新校區來校路線圖:
- http://bbs.itheima.com/thread-347847-1-1.html