2011-09-06 46 views
2
RowID  TimeReceived TimeRead tbl_user_UserID  tbl_message_MsgID 

    5  2011-09-06 11:16:20 NULL    2    1 
    6  2011-09-06 11:17:04 NULL    3    1 
    7  2011-09-06 11:17:19 NULL    100    1 

這是我的表如何獲得行計數當一個特定的字段爲空

command = new MySqlCommand("SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead= NULL AND [email protected]", connectionString); 
     command.Parameters.Add("@value1", MySqlDbType.Int32, 25); 
     command.Parameters["@value1"].Value = MessageID; 
     int nnnID = Convert.ToInt32(command.ExecuteScalar()); 

我要計數的行,時間讀爲空,它給我0作爲輸出,它應該是3.我哪裏錯了。我已將讀取時間的默認值設置爲空。

+0

只有在ANSI_NULLS關閉的情況下才能正常工作 – V4Vendetta

+0

爲什麼使用COUNT(Distinct RowID)而不是COUNT(*)?不清楚你的問題的其餘部分是否需要。 –

回答

1

你的SQL不正確。您可以通過使用IS NULL檢查NULL:

command = new MySqlCommand("SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead IS NULL AND [email protected]", connectionString); 
     command.Parameters.Add("@value1", MySqlDbType.Int32, 25); 
     command.Parameters["@value1"].Value = MessageID; 
     int nnnID = Convert.ToInt32(command.ExecuteScalar()); 
3

查詢用於獲取計數

select count(Distinct RowID) from table where TimeRead is null 
+0

同意,TimeRead = null始終爲false。沒有什麼等於空。 –

+0

該查詢將始終返回「0」 –

2

使用 「is NULL」 而不是 「= NULL

SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead is NULL ... 

還要檢查,如果你的參數@value1是正確的!

相關問題