所以我有以下情况:如您所见,某些字段为空,因此我想在插入记录之前检查表中是否已经存在goal该记录,我要插入的记录包含与表中已经可用的记录完全相同的结构。这是我的代码:public bool CheckGoalExist(Goal goal, Goal.GoalType type, int matchId){ using (MySqlConnection connection = new DBConnection().Connect()) { using (MySqlCommand command = new MySqlCommand()) { command.Connection = connection; command.CommandText = "SELECT COUNT(*) FROM goal " + "WHERE player_marker_id = @player_marker_id AND " + "team_id = @team_id AND " + "player_assist_id = @player_assist_id AND " + "match_id = @match_id AND " + "minute = @minute AND " + "type = @type"; command.Parameters.AddWithValue("@team_id", goal.TeamId); command.Parameters.AddWithValue("@player_marker_id", goal.MarkerPlayer.Id); command.Parameters.AddWithValue("@player_assist_id", goal.AssistPlayer?.Id); command.Parameters.AddWithValue("@match_id", matchId); command.Parameters.AddWithValue("@minute", goal.Minute); command.Parameters.AddWithValue("@type", GetGoalTypeId(type)); return Convert.ToBoolean(command.ExecuteScalar()); } }}这将返回,false但值goal是这样的:TeamId = 95MarkerPlayer.Id = 122AssistPlaer = nullmatchId = 2564940Minute = 82'Type = 5为什么返回false?
3 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
如果AssistPlaer是null,则不能使用=. 您需要检查参数是否为null第一个。这是一个带有or语句的常用方法:
command.CommandText = "SELECT COUNT(*) FROM goal " +
"WHERE player_marker_id = @player_marker_id AND " +
"team_id = @team_id AND " +
"(@player_assist_id is null or player_assist_id = @player_assist_id) AND " +
"match_id = @match_id AND " +
"minute = @minute AND " +
"type = @type";
对于其他潜在null值,您可能也需要这样做。
白衣非少年
TA贡献1155条经验 获得超0个赞
由于“AssistPlaer”为“NULL”,SQL 中的查询不能使用等号运算符“=”,而必须使用“IS”或“IS NOT”与“NULL”进行比较。
您的查询指出:
player_assist_id = @player_assist_id
但是“NULL”值不响应相等的运算符,测试它是否为空的唯一方法是:
player_assist_id IS NULL
所以在您的查询中,您可以使用以下内容绕过它:
(@player_assist_id IS NULL AND player_assist_id IS NULL) OR (player_assist_id = @player_assist_id)
将此行为应用于可以包含“NULL”的任何列。
- 3 回答
- 0 关注
- 140 浏览
添加回答
举报
0/150
提交
取消