SQL中union, EXCEPT 和 INTERSECT使用方法
来源:互联网 发布:中国抑郁症数据 编辑:程序博客网 时间:2024/04/28 17:40
这三个放在一起是有理由的,因为他们都是操作两个或多个结果集,并且这些结果集有如下限制:
所有查询中的列数和列的顺序必须相同.
数据类型必须兼容.
并且它们都是处理于多个结果集中有重复数据的问题
所有查询中的列数和列的顺序必须相同.
数据类型必须兼容.
并且它们都是处理于多个结果集中有重复数据的问题
首先还是创建测试环境
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}
0 0
- SQL中union, EXCEPT 和 INTERSECT使用方法
- SQL中union,except,intersect使用方法
- SQL中Union,Intersect,Except的区别
- SQL基础--UNION EXCEPT INTERSECT
- SQL中 EXCEPT和INTERSECT用法
- sql之union,intersect,except语句
- SQL基础——UNION, EXCEPT, INTERSECT
- LINQ to SQL语句 Union/Intersect/Except
- SQL中union, intersect 和 minus
- SQL中 EXCEPT、INTERSECT用法
- SQL中 EXCEPT、INTERSECT用法
- EXCEPT 和 INTERSECT (Transact-SQL)
- sql except和INTERSECT用法
- [Sql]EXCEPT 和 INTERSECT关键字
- UNION, INTERSECT, EXCEPT
- UNION, INTERSECT, EXCEPT
- SQL Server 2005中Except和Intersect的用法示例
- SQL Server 中关于EXCEPT和INTERSECT的用法
- Java-快速排序
- unity3d实现LOL中的相机控制功能
- 机器学习--特征选择
- 动态运行时类型的显式转换
- Vijava 学习笔记之(VirtualMachine 获取网卡配置信息)
- SQL中union, EXCEPT 和 INTERSECT使用方法
- “Ceph浅析”系列之二——Ceph的设计思想
- 图形处理(一)离散指数映射参数化-Siggraph 2006
- 多线程执行CPU过高问题
- 拓扑排序(topological sorting)
- VS2010 C++ 操作Excel表格的编程实现
- 如何终止线程的运行
- Maven导入oracle驱动
- ajax中的脚本标签技巧