如何在特定字段为空时获取行计数

时间:2011-09-06 11:54:41

标签: c# asp.net sql null

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 tbl_message_MsgID=@Value1", connectionString);
         command.Parameters.Add("@value1", MySqlDbType.Int32, 25);
         command.Parameters["@value1"].Value = MessageID;
         int nnnID = Convert.ToInt32(command.ExecuteScalar());

我想计算时间读取为空的行,它给出0作为输出,它应该是3.我在哪里出错了。我已将读取的时间的默认值设置为空。

3 个答案:

答案 0 :(得分:3)

查询获取计数

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

答案 1 :(得分:2)

使用“is NULL”代替“= NULL

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

同时检查参数@value1是否正确!

答案 2 :(得分:1)

您的SQL不正确。您可以使用IS NULL

检查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());