2010-07-26 99 views
6

我已經寫了並且通過了70-433(SQL 2008 MCTS考試),並且當我意識到我一直在做什麼INTERSECTWHERE IN子查詢以及EXCEPTWHERE NOT IN子查詢。INTERSECT和WHERE IN有什麼區別?

使用新命令而不是子查詢有什麼區別嗎?

回答

4

INTERSECTEXCEPT比較返回的行中的所有選定值,而WHERE INWHERE NOT IN一次只比較一列。

SELECT name,date from customers 
EXCEPT 
SELECT name, date from orders 
+0

謝謝你,先生。你是一個紳士和一個數據庫管理員。 豎起大拇指。 – callisto 2010-07-26 14:05:56

4

有它們處理NULL小號

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL), 
    T2 AS (SELECT 2 AS COL UNION SELECT NULL) 
SELECT * FROM T1 
INTERSECT 
SELECT * FROM T2; 

一個重要的區別。

COL 
----------- 
NULL 

(1 row(s) affected) 

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL), 
    T2 AS (SELECT 2 AS COL UNION SELECT NULL) 
SELECT * FROM T1 WHERE COL IN (SELECT COL FROM T2) ; 

COL 
----------- 

(0 row(s) affected) 

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL), 
    T2 AS (SELECT 2 AS COL UNION SELECT NULL) 
SELECT * FROM T1 
EXCEPT 
SELECT * FROM T2; 

COL 
----------- 
1 

(1 row(s) affected) 

WITH T1 AS(SELECT 1 AS COL UNION SELECT NULL), 
    T2 AS (SELECT 2 AS COL UNION SELECT NULL) 
SELECT * FROM T1 WHERE COL NOT IN (SELECT COL FROM T2); 

COL 
----------- 

(0 row(s) affected)