下面我會比較 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)