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

select * from temptable1
select * from temptable2

[/code]

两个表的初始结果如下


非常简单的两个表
,
列数和列顺序一样
.
而数据中有一条数据相同
,
这里的相同时完全相同
,
包括主键
,
我这里的主键是标识列
,
所以插入的顺序也一样
,
若不是标识列
,
则随意
,
只要保证
有数据完全一致
,
就可以说他们是重复的数据
,
这样用上面
3
个运算词才会有效
.
先来看看
UNION

UNION ALL
最全最热最专业的文档类资源,文库一网打尽


select * from temptable1
union
select * from temptable2

select * from temptable1
union all
select * from temptable2




ALL
关键字是完全整合两个结果集
,
而无

ALL
是在之前的基础上去重了
,
所以第一个查
询中
{id:1, price:3}
只会显示一条
,
结果如下
:



在来看看
EXCEPT,
也是去重的
,
但是它在去掉两个或多个集合中重复数据的之后
,
只会保
留第一个结果集中的数据


select * from temptable1
except
select * from temptable2



其实也是查询表
A,
看表
A
的数据在表
B
中是否存在
,
如果存在
,
则删掉


INTERSECT
比较好理解
,
就是查询两个结果集的并集
,
利用上面的数据
,
查询到的结果只
有一条
,
就是
{id:1, price:3}

你可能感兴趣的:(SQL)