SQL Server 2005中的except/intersect和outer apply

轉: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

我們的目的是從表#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)

當然還有使用left join/right join/full join的幾種寫法,但是無一例外,都是比較冗長的。其實在SQL Server 2005增加了一種新的方法,可以幫助我們很簡單、很簡潔的完成任務:

select * from #b
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也可以完成這個任務。

如果我們要尋找兩個表的交集呢?那麼在2005就可以用intersect關鍵字:

select * from #b
intersect
select * from #a

ID
-----------
1

(
1 row(s) affected)
發佈了33 篇原創文章 · 獲贊 10 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章