2013-11-26 30 views
2

Customers表如果在列表中的值是空

CUSTOMER_ID FIRST_NAME  LAST_NAME   DOB  PHONE 

1   John   Brown   1/1/1965 800-555-1211 
2   Cynthia   Orange  2/5/1968 800-555-1212 
3   Steve   White   3/16/1971 800-555-1213 
4   Gail   Black     800-555-1214 
5   Doreen   Blue   5/20/1970 
6   Fred   Brown   1/1/1970 800-555-1215 

如果運行查詢

select * from customers where customer_id not in (2,3,5,NULL); 

我得到的輸出沒有行返回NOT IN返回false .....請幫我理清這個問題了..

+0

請解釋??????那是什麼意思 ??? –

+0

我的意思是說爲什麼輸出沒有行返回。 – Nikhil

+0

這不是問問題夥伴的方式.... –

回答

4

你被SQL 3值邏輯咬了。

對於customer_id爲2,3或5的行,WHERE子句的計算結果爲false,如您所期望的那樣。

對於其他行,它的計算結果UNKNOWN(或NULL;我不知道,如果甲骨文區分開來),爲true。

如果IN表達式擴展爲(customer_id != 2) AND (customer_id != 3) AND (customer_id != 5) AND (customer_id != NULL),這可能會更清楚。對於1,4或6的customer_id,前三個子表達式按照您的預期評估爲真。但是最後一個評估爲未知,因爲NULL(未知值的標記)可能「真正」是1,4或6.因此,整個表達式具有未知的真值。 SELECT語句將只返回WHERE子句肯定爲真,而不是未知的行。

你可以通過查詢得到你想要的結果。

select * from customers where customer_id not in (2, 3, 5) and customer_id is not null; 

然而,看來你customer_id是自動增量列,並不能真正爲空反正。如果是這樣,只寫:

select * from customers where customer_id not in (2, 3, 5); 
0

試試這個

select * from customers where customer_id not in (2,3,5); 
2

在這種特定情況下,您正在尋找

select * from customers where customer_id not in (2,3,5); 

空會在這種情況下可以省略。

爲什麼?

如所解釋的here,A不是在statment確實,在這種情況下執行以下操作:

select * where CustomerID <> 2 and CustomerID <> 3 and CustomerID <> 5 and CustomerID <> NULL 

使用默認ANSI_NULLS符號上,將導致UNKNOWN的customerID <> NULL。當SQL有一個UNKNOWN時,它將不返回任何行。當它關閉時,它將返回true。

你必須在這一點上兩個選項:

  1. 更改聲明,沒有在一個null
  2. 更改數據庫引擎有ANSI_NULLS關閉

我想,我會在這種情況下更容易的選擇...

+0

但是當我執行這個查詢時我得到了一個輸出select * from customers where customer_id in(2,3,5,NULL) – Nikhil

0

你的陳述

select * from customers where customer_id in (2,3,5,NULL) 

等於

select * where CustomerID = 2 or CustomerID = 3 or CustomerID = 5 or CustomerID = NULL 

最後一個表達式 「客戶id = NULL」 返回總是假的,但由於OR這種情況確實會影響結果。

你必須把它寫這樣的:

select * from customers where customer_id in (2,3,5) or customer_id IS NULL 
+0

'CustomerId = NULL'總是返回null /未知,不是假。 – dan04

相關問題