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会去重。

猜你喜欢

转载自www.cnblogs.com/ziqiumeng/p/10303246.html
今日推荐