How to get row count when a particular field is empty
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 开发者_如何学Go 2011-09-06 11:17:19 NULL 100 1
This is my table
command = new MySqlCommand("SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead= NULL AND tbl_message_MsgID=@Value1", connectionString);
command.Parameters.Add("@value1", MySqlDbType.Int32, 25);
command.Parameters["@value1"].Value = MessageID;
int nnnID = Convert.ToInt32(command.ExecuteScalar());
I want to count the row where time read is null, it gives me 0 as output where it should be 3. Where am I going wrong. i have set the default value for time read as null.
Query for getting count
select count(Distinct RowID) from table where TimeRead is null
Use "is NULL
" instead of "= NULL
"
SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead is NULL ...
Also check if your parameter @value1
is correct!
Your SQL is incorrect. You can check for NULL by using IS NULL
:
command = new MySqlCommand("SELECT COUNT(Distinct RowID) FROM tbl_usermessage WHERE TimeRead IS NULL AND tbl_message_MsgID=@Value1", connectionString);
command.Parameters.Add("@value1", MySqlDbType.Int32, 25);
command.Parameters["@value1"].Value = MessageID;
int nnnID = Convert.ToInt32(command.ExecuteScalar());
精彩评论