SQL Server中except和intersect用法

except是A集合减去B集合的结果;intersect是A集合和B集合的交集;都是返回的是非重复值,很多属性都和union类似。

还是以student为例

select * from student;

image

select * into student1 from student;
go
insert into student1 values('aaa',20,'Js'),('bbb',30,'js'),('ccc',40,'sh');
go
insert into student1 values('aa',10,'JiangSu');
go
select * from student1 order by 1;

image

student1中name为aa两行是重复的;

student1还比student多加了三行,aaa,bbb,ccc

select * from student1
except
select * from student

image

结果只有aaa,bbb,ccc;没有aa那行

select * from student1
intersect
select * from student

image

只有student表中的13行,aa那行没有重复

这里只注重返回结果是没有重复行的,except和intersect 暂时没有all选项,这点和union不同。

关于except、intersect、union的优先级验证:

select * into student2 from student1;
go
delete from student2 where name='aaa';
go
select * from student2 order by 1;
go

image

student2的表比student1表少一行aaa的记录

select * from student2
except
select * from student1
intersect
select * from student

image

如果你怀疑student2记录少于student1的记录,except有问题的话,我们互换下

select * from student1
except
select * from student2
intersect
select * from student

image

intersect的优先级高于except

同样的原理测试,intersect的优先级也高于union

except和union的级别是相同的,顺序执行的。

posted @ 2014-06-05 11:51  cnmarkao  阅读(4065)  评论(0编辑  收藏  举报