2012-02-03 95 views
0

對於我正在嘗試編寫的相當基本的查詢有問題。計數(*)不適用於where子句

select count (p_id) as mycustomer from person where date_active = null; 

哪個不行。 (運行,但返回0)但是,下面的語句(並返回一個數字),任何人都可以幫忙嗎?

select count (p_id) as mycustomer from person wher date_active > '1-MAY-09'; 

我試圖找到在具有date_active爲空表p_ids的總數。 (他們確實存在,我可以看到他們!) 感謝

+4

'null'在SQL中永遠不會等於'null'。我們還有其他問題嗎? – 2012-02-03 10:44:16

+0

道歉,我對這個東西相當生疏,而尋找類似的問題並沒有幫助。 :( – GrumP 2012-02-03 10:48:42

回答

4

我認爲你需要使用:

select count (p_id) as mycustomer from person where date_active is null; 
+0

謝謝,我想通了。對於愚蠢的問題道歉! – GrumP 2012-02-03 10:50:27

1

請嘗試以下

select count (p_id) as mycustomer from person where date_active is null; 

= null是不正確的,你想要什麼也不會做。這link提供了更多的細節

1
select count (p_id) as mycustomer from person where date_active IS null; 

(注意,IS NULL運算符代替=)

+0

@onedaywhen你是絕對正確的! – 2012-02-03 12:10:01

1

必須使用is oprator找到空:

select count (p_id) as mycustomer from person where date_active is null; 

NULL不是一個值(它表示無效),所以你不能使用像=,!=,<,>等標量操作符與NULL結合使用。

1

這應該工作:

select count (p_id) as mycustomer from person where date_active IS null; 
0

SQL不與二進制邏輯工作(僅truefalse)。它適用於(至少)三元邏輯(true,falsenull)。第三個值使邏輯條件的評估複雜化(例如,您在條件中有=)。
基本上,包括一個空的表達式,將返回一個空值,並且由於null是從來沒有true,查詢將不會返回任何行,就像如果你寫

select count (p_id) as mycustomer from person where 1 = 2 

要解決此有是一些特殊的語法結構,最常見的是is nullis not null條件。因此,作爲其他的答案中指出,要得到空值,你需要寫

select count (p_id) as mycustomer from person where date_active is null 

約零點有趣的是,它們既不等於沒有不相等的到其他空值。

select * from person where null=null 

select * from person where null!=null 

都不會返回任何行。

+0

「涉及null的任何表達式,將返回一個空值」 - 一些表達式可能**評估爲UNKNOWN * *(細微差別):有例外情況,例如'IS NULL'運算符只計算爲TRUE或FALSE。UNKNOWN是三值邏輯中的邏輯值,而null是值的佔位符。 – onedaywhen 2012-02-03 11:14:57