正确的查询无法使用MySqlDataReader

时间:2019-03-16 14:56:38

标签: c# mysql

所以我想弄清楚这一点,特别是我有一个使用PhpMyAdmin才能完美运行的查询:

SELECT tt.team_id, (CASE WHEN t.id IS NULL THEN 0 ELSE 1 END) as exist FROM(SELECT 13048 as team_id  UNION ALL SELECT 17058 UNION ALL SELECT 38809 UNION ALL SELECT 8216 UNION ALL SELECT 5466) tt LEFT JOIN team t on t.id = tt.team_id WHERE t.id IS NULL OR t.update_at < DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)

无论如何,我从Visual Studio收到此错误:

  

MySql.Data.MySqlClient.MySqlException:'您的SQL语法有错误;在''UNION ALL SELECT 17058 UNION ALL SELECT 38809 UNION ALL SELECT 8216 UNION ALL'的第1行'附近检查与您的MySQL服务器版本相对应的手册以使用正确的语法

此错误的发生日期:

 using (MySqlDataReader reader = command.ExecuteReader())

我以这种方式设置查询:

command.CommandText = "SELECT tt.team_id, " +
    "(CASE WHEN t.id IS NULL THEN 0 ELSE 1 END) as exist " +
    "FROM(SELECT @first as team_id @others) tt LEFT JOIN team t on t.id = tt.team_id " +
    "WHERE t.id IS NULL OR " +
    "t.update_at < DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)";

command.Parameters.Add("@first", MySqlDbType.Int32).Value = teams.First().Id;
command.Parameters.Add("@others", MySqlDbType.String).Value = string.Concat(teams.Skip(1).Select(c => " UNION ALL SELECT " + c.Id));

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

这是我如何构建动态参数列表以传递给您的查询的方法。
警告,未经测试,但这应该会产生预期的输出

// Command text with a placeholder where we insert the dynamic text
string cmd = @"SELECT tt.team_id, 
                      (CASE WHEN t.id IS NULL THEN 0 ELSE 1 END) as exist 
               FROM (SELECT {texttoreplace}) tt  
               LEFT JOIN team t on t.id = tt.team_id WHERE t.id IS NULL 
                     OR t.update_at < DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)";

int prmCounter = 1;

// Where we keep the text to insert at the appropriate place
StringBuilder unions = new StringBuilder();
// Where we keep the parameters to add at the MySqlCommand
List<MySqlParameter> prms = new List<MySqlParameter>();

// First parameter
MySqlParameter pr = new MySqlParameter("@first", MySqlDbType.Int32) { Value = teams.First().id};
prms.Add(pr);
unions.Append($" @first as team_id ");

// Loop over your IDs and build parameters and text
foreach (var t in teams.Skip(1))
{
    // Giving an unique name to the parameter
    string placeholder = "@p" + prmCounter;
    unions.Append($" UNION ALL SELECT {placeholder}");
    pr = new MySqlParameter(placeholder, MySqlDbType.Int32) { Value = t.id};
    prms.Add(pr);
    prmCounter++;
}
// Add all the required parameters
command.Parameters.AddRange(prms.ToArray());
// Replace the placeholder with the built text
cmd = cmd.Replace("{texttoreplace}",  unions.ToString());