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
select * from temptable1
select * from temptable2
 
两个表的初始结果例如以下
 
很easy的两个表,列数和列顺序一样. 而数据中有一条数据同样,这里的同样时全然同样,包含主键,我这里的主键是标识列, 所以插入的顺序也一样, 若不是标识列,则任意,仅仅要保证有数据全然一致,就能够说他们是反复的数据, 这样用上面3个运算词才会有效.
先来看看UNION和UNION ALL
select * from temptable1
union
select * from temptable2
select * from temptable1
union all
select * from temptable2
 
有 ALL keyword是全然整合两个结果集,而无 ALL 是在之前的基础上去重了,所以第一个查询中{id:1, price:3}仅仅会显示一条,结果例如以下:
 
 
 在来看看EXCEPT, 也是去重的, 可是它在去掉两个或多个集合中反复数据的之后, 仅仅会保留第一个结果集中的数据
select * from temptable1
except
select * from temptable2
 
 
 
事实上也是查询表A, 看表A的数据在表B中是否存在, 假设存在, 则删掉
而INTERSECT比較好理解, 就是查询两个结果集的并集, 使用上述数据,查询的结果,以仅具有一个, 那是,{id:1, price:3}

版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4839965.html