SQL Server 2005中的except/intersect和outer apply
来源:互联网 发布:内向工作知乎 编辑:程序博客网 时间:2024/05/18 23:55
转:http://www.cnblogs.com/fanweixiao/archive/2008/03/30/1129482.html
首先,建立两个表:
CREATE TABLE #a (ID INT)
INSERT INTO #a VALUES (1)
INSERT INTO #a VALUES (2)
INSERT INTO #a VALUES (null)
CREATE TABLE #b (ID INT)
INSERT INTO #b VALUES (1)
INSERT INTO #b VALUES (3)
INSERT INTO #a VALUES (1)
INSERT INTO #a VALUES (2)
INSERT INTO #a VALUES (null)
CREATE TABLE #b (ID INT)
INSERT INTO #b VALUES (1)
INSERT INTO #b VALUES (3)
我们的目的是从表#b中取出ID不在表#a的记录。
如果不看具体的insert的内容,单单看这个需求,可能很多朋友就会写出这个sql了:
select * from #b where id not in (select id from #a)
但是根据上述插入的记录,这个sql检索的结果不是我们期待的ID=3的记录,而是什么都没有返回。原因很简单:在子查询select id from #a中返回了null,而null是不能跟任何值比较的。
那么您肯定会有下面的多种写法了:
select * from #b where id not in (select id from #a where id is not null)
select * from #b b where b.id not in (select id from #a a where a.id=b.id)
select * from #b b where not exists (select 1 from #a a where a.id=b.id)
select * from #b b where b.id not in (select id from #a a where a.id=b.id)
select * from #b b where not exists (select 1 from #a a where a.id=b.id)
当然还有使用left join/right join/full join的几种写法,但是无一例外,都是比较冗长的。其实在SQL Server 2005增加了一种新的方法,可以帮助我们很简单、很简洁的完成任务:
select * from #b
except
select * from #a
except
select * from #a
我不知道在SQL Server 2008里还有没有什么更酷的方法,但是我想这个应该是最简洁的实现了。当然,在2005里还有一种方法可以实现:
select * from #b b
outer apply
(select id from #a a where a.id=b.id) k
where k.id is null
outer apply
(select id from #a a where a.id=b.id) k
where k.id is null
outer apply也可以完成这个任务。
如果我们要寻找两个表的交集呢?那么在2005就可以用intersect关键字:
select * from #b
intersect
select * from #a
ID
-----------
1
(1 row(s) affected)
intersect
select * from #a
ID
-----------
1
(1 row(s) affected)
0 0
- SQL Server 2005中的except/intersect和outer apply
- SQL Server 2005中的except/intersect和outer apply
- SQL Server 2005中的except/intersect和outer apply
- sql server 2005中的except和INTERSECT运算
- SQL Server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算
- sql server 2005中的except和INTERSECT运算(附加Compute by子句)
- SQL Server 2005中Except和Intersect的用法示例
- SQL Server 2005 EXCEPT和INTERSECT运算符
- SQL Server 2005 EXCEPT和INTERSECT运算符
- SQL Server cross apply 和outer apply
- SQL SERVER 2008的EXCEPT和INTERSECT
- SQL语句中的EXCEPT和INTERSECT
- SQL server Outer apply
- 关于xcode7升级以后,无法archive,或者archive后xcode闪退的问题处理方案
- 【LeetCode OJ 007】Reverse Integer
- ProgressBar样式的定义
- LeetCode H-Index II 数组+二分
- HDU 5525 Product
- SQL Server 2005中的except/intersect和outer apply
- 杭电1166敌兵布阵
- JS下拉列表,随着省份的改变,城市也会有所改变
- 最基础的MarkDown使用
- DDL、DML和DCL的理解
- 分享一个VBA连接mysql数据库的方法
- 有重复元素的排列问题
- .net之jquery操作gridview中的数据
- ViewController 瘦身的另一种解决方案(转)