检查记录是否存在,如果字段为null,则始终返回false

时间:2018-06-20 12:41:18

标签: c# mysql sql

所以我有以下情况:

enter image description here

如您所见,某些字段为null,因此我想在插入记录之前检查一下,该记录是否已经存在于表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 = 95
MarkerPlayer.Id = 122
AssistPlaer = null
matchId = 2564940
Minute = 82'
Type = 5

为什么返回假?

3 个答案:

答案 0 :(得分:5)

如果AssistPlaernull,则不能使用=。您首先需要检查参数是否为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值,您可能也需要这样做。

答案 1 :(得分:1)

由于“ AssistPlaer”为“ NULL”,SQL中的查询不能使用相等的运算符“ =”,但必须使用“ IS”或“ IS NOT”与“ NULL”进行比较。

您的查询状态:

player_assist_id = @player_assist_id

但是“ NULL”值不会响应相等的运算符,测试它是否为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”的任何列。

答案 2 :(得分:0)

如果您不知道属性值是否为NULL,则可以使用IFNULL字符串函数,以便它将NULL值替换为0或您在该特定列中定义的其他值。