【问题标题】:Move rows from table to table将行从表移动到表
【发布时间】:2013-05-18 13:53:17
【问题描述】:

我尝试将过期的行从一个表移动到另一个表:

MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();

cmd.Connection = connect;
cmd.Connection.Open();

string commandLine = @"INSERT INTO history SELECT clientid,userid,startdate,
                       enddate,first,city,imgurl,phone,type,seen 
                       FROM events WHERE startdate<now();";

cmd.CommandText = commandLine;

cmd.ExecuteNonQuery();
cmd.Connection.Close();

表完全相同(在每个表中,我都有带有主键的 id 列,具有自动增量),当我运行它时,我得到了这个异常:

Column count doesn't match value count at row 1

知道为什么会崩溃吗?

【问题讨论】:

  • event 中的列数返回的列数比history 预期的多/少。你能张贴两张表吗?
  • 为什么需要在历史表中有一个 auto_increment 列?

标签: c# mysql .net sql


【解决方案1】:

您收到错误的原因是表上的列数与插入的值数不匹配。当您要插入的表上有一个自动递增的列时,这很常见。

为了解决此问题,您需要指定将插入值的列名。例如,

INSERT INTO history (col1, col2,....) // << specify column names here
SELECT clientid, userid, startdate, enddate, first, 
       city, imgurl, phone, type, seen 
FROM   events 
WHERE  startdate < now()

我不太确定表 history 的列名,因此您需要将列名更改为表上的有效名称。

例如,您在表历史记录中有一个自动递增的列,并且您想保持查询不变,您可以在 SELECT 语句上传递 NULL 以匹配列总数与价值观。例如,

INSERT INTO history 
SELECT NULL, clientid, userid, startdate, enddate, first, 
       city, imgurl, phone, type, seen 
FROM   events 
WHERE  startdate < now()

请记住,如果您不指定列名,则值的顺序很重要。

【讨论】:

    【解决方案2】:

    试试:

    string commandLine = @"INSERT INTO history (clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen) SELECT clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen FROM events WHERE startdate<now();";
    

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多