检查记录是否存在如果字段为空则返回always false

ztmd8pv5  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(415)

所以我有以下情况:

正如您所看到的,有些字段是空的,所以我想在插入记录之前检查一下表中是否已经存在这个字段 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

为什么返回false?

muk1a3rh

muk1a3rh1#

如果您不知道属性值是否为null,那么可以使用ifnull string函数,以便它将null值替换为0或您在该特定列中定义的其他值。

piah890a

piah890a2#

如果 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 价值观。

11dmarpk

11dmarpk3#

由于“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”的列。

相关问题