【问题标题】:INSERT INTO...SELECT for all MySQL columns所有 MySQL 列的 INSERT INTO...SELECT
【发布时间】:2011-07-12 07:37:28
【问题描述】:

我正在尝试从以下位置移动旧数据:

this_table >> this_table_archive

复制所有列。这个我试过了,还是不行:

INSERT INTO this_table_archive (*) VALUES (SELECT * FROM this_table WHERE entry_date < '2011-01-01 00:00:00');

注意:这些表是相同的,并且将id 设置为主键。

【问题讨论】:

标签: mysql select insert-into


【解决方案1】:

More Examples & Detail

    INSERT INTO vendors (
     name, 
     phone, 
     addressLine1,
     addressLine2,
     city,
     state,
     postalCode,
     country,
     customer_id
 )
 SELECT 
     name,
     phone,
     addressLine1,
     addressLine2,
     city,
     state ,
     postalCode,
     country,
     customer_id
 FROM 
     customers;

【讨论】:

    【解决方案2】:

    除了马克拜尔斯的回答:

    有时您还想插入 硬编码 详细信息,否则可能会出现唯一约束失败等。因此,请在覆盖列的某些值的情况下使用以下内容。

    INSERT INTO matrimony_domain_details (domain, type, logo_path)
    SELECT 'www.example.com', type, logo_path
    FROM matrimony_domain_details
    WHERE id = 367
    

    这里 domain 值由我以硬编码方式添加,以摆脱唯一约束。

    【讨论】:

      【解决方案3】:

      对于语法,它看起来像这样(省略列列表以暗示“全部”)

      INSERT INTO this_table_archive
      SELECT *
      FROM this_table
      WHERE entry_date < '2011-01-01 00:00:00'
      

      如果存档表中已有数据,则用于避免主键错误

      INSERT INTO this_table_archive
      SELECT t.*
      FROM this_table t
      LEFT JOIN this_table_archive a on a.id=t.id
      WHERE t.entry_date < '2011-01-01 00:00:00'
        AND a.id is null  # does not yet exist in archive
      

      【讨论】:

      • +1 用于左连接以避免主键冲突。
      【解决方案4】:

      值位不需要 double () 吗?如果不试试这个(虽然一定有更好的方法

      insert into this_table_archive (id, field_1, field_2, field_3) 
      values
      ((select id from this_table where entry_date < '2001-01-01'), 
      ((select field_1 from this_table where entry_date < '2001-01-01'), 
      ((select field_2 from this_table where entry_date < '2001-01-01'), 
      ((select field_3 from this_table where entry_date < '2001-01-01'));
      

      【讨论】:

      • OP 使用的是INSERT INTO .. SELECT FROM,而不是INSERT INTO .. VALUES。不同的功能。
      【解决方案5】:

      manual 中描述了正确的语法。试试这个:

      INSERT INTO this_table_archive (col1, col2, ..., coln)
      SELECT col1, col2, ..., coln
      FROM this_table
      WHERE entry_date < '2011-01-01 00:00:00';
      

      如果 id 列是自动增量列,并且您在两个表中都已经有一些数据,那么在某些情况下,您可能希望从列列表中省略 id 并生成新的 id,以避免插入已经存在的 id在原始表中。如果您的目标表是空的,那么这将不是问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-25
        • 2012-01-08
        • 2019-03-14
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-08
        相关资源
        最近更新 更多