SQL SERVER EXCEPT 和 INTERSECT


下面我會比較 EXCEPT/INTERSECT跟 not in/in的區別,其實最主要的區別就是EXCEPT/INTERSECT可以去重,相當於 not in/in加了distinct關鍵字,這點類似於union和union all

1、創建測試數據:

create table #tempTable1 (id int , price int)
create table #tempTable2 (id int , price int)
insert into #tempTable1 select 3,1 union all select 3,1 union all select 1,1 union all select 1,1 union all select 1,2 
insert into #tempTable2 select 1,1 union all select 1,1 union all select 2,1 union all select 1,5

2、單列和所有列比對

--所有列對比
select * from #temptable1
except 
select * from #temptable2
--只比對ID這一列
select ID from #temptable1
except
select ID from #temptable2

 

3、跟NOT IN比較:將重復值去掉了

select ID from #temptable1
except
select ID from #temptable2
---------------------
select ID from #temptable1
WHERE ID NOT IN(select ID from #temptable2)

4、INTERSECT跟in語句也是相似的,只是INTERSECT會去重。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM