SQL中union, EXCEPT 和 INTERSECT使用方法,unionintersect

來源:互聯網
上載者:User

SQL中union, EXCEPT 和 INTERSECT使用方法,unionintersect
這三個放在一起是有理由的,因為他們都是操作兩個或多個結果集,並且這些結果集有如下限制:
所有查詢中的列數和列的順序必須相同. 
資料類型必須相容. 
並且它們都是處理於多個結果集中有重複資料的問題首先還是建立測試環境use tempdbcreate table tempTable1 (id int primary key identity, price int)
create table tempTable2 (id int primary key identity, price int)
insert into tempTable1 select 3 union all select 1 union all select 2 union all select 3 
insert into tempTable2 select 3 union all select 4 union all select 1 union all select 2select * from temptable1
select * from temptable2 兩個表的初始結果如下 非常簡單的兩個表,列數和列順序一樣. 而資料中有一條資料相同,這裡的相同時完全相同,包括主鍵,我這裡的主鍵是識別欄位, 所以插入的順序也一樣, 若不是識別欄位,則隨意,只要保證有資料完全一致,就可以說他們是重複的資料, 這樣用上面3個運算詞才會有效.先來看看UNION和UNION ALLselect * from temptable1
union
select * from temptable2select * from temptable1
union all
select * from temptable2
 有 ALL 關鍵字是完全整合兩個結果集,而無 ALL 是在之前的基礎上去重了,所以第一個查詢中{id:1, price:3}只會顯示一條,結果如下:   在來看看EXCEPT, 也是去重的, 但是它在去掉兩個或多個集合中重複資料的之後, 只會保留第一個結果集中的資料select * from temptable1
except
select * from temptable2   其實也是查詢表A, 看錶A的資料在表B中是否存在, 如果存在, 則刪掉而INTERSECT比較好理解, 就是查詢兩個結果集的並集, 利用上面的資料,查詢到的結果只有一條, 就是{id:1, price:3}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.