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