SQL中union, EXCEPT 和 INTERSECT使用方法
SQL中的UNION, EXCEPT 和 INTERSECT做下演示:
这三个放在一起是有理由的,因为他们都是操作两个或多个结果集,并且这些结果集有如下限制:
所有查询中的列数和列的顺序必须相同.
数据类型必须兼容.
并且它们都是处理于多个结果集中有重复数据的问题
所有查询中的列数和列的顺序必须相同.
数据类型必须兼容.
并且它们都是处理于多个结果集中有重复数据的问题
首先还是创建测试环境
use tempdb
create table tempTable1 (id int primary key identity, price int)
create table tempTable2 (id int primary key identity, price int)
insert into tempTable1 select 3 union all select 1 union all select 2 union all select 3
insert into tempTable2 select 3 union all select 4 union all select 1 union all select 2
create table tempTable2 (id int primary key identity, price int)
insert into tempTable1 select 3 union all select 1 union all select 2 union all select 3
insert into tempTable2 select 3 union all select 4 union all select 1 union all select 2
select * from temptable1
select * from temptable2
select * from temptable2
两个表的初始结果如下
非常简单的两个表,列数和列顺序一样. 而数据中有一条数据相同,这里的相同时完全相同,包括主键,我这里的主键是标识列, 所以插入的顺序也一样, 若不是标识列,则随意,只要保证有数据完全一致,就可以说他们是重复的数据, 这样用上面3个运算词才会有效.
先来看看UNION和UNION ALL
select * from temptable1
union
select * from temptable2
union
select * from temptable2
select * from temptable1
union all
select * from temptable2
union all
select * from temptable2
有 ALL 关键字是完全整合两个结果集,而无 ALL 是在之前的基础上去重了,所以第一个查询中{id:1, price:3}只会显示一条,结果如下:
在来看看EXCEPT, 也是去重的, 但是它在去掉两个或多个集合中重复数据的之后, 只会保留第一个结果集中的数据
select * from temptable1
except
select * from temptable2
except
select * from temptable2
其实也是查询表A, 看表A的数据在表B中是否存在, 如果存在, 则删掉
而INTERSECT比较好理解, 就是查询两个结果集的并集, 利用上面的数据,查询到的结果只有一条, 就是{id:1, price:3}, 这里就不给出代码和结果图

浙公网安备 33010602011771号