插入到…为所有MySQL列选择

插入到…为所有MySQL列选择,mysql,select,insert-into,Mysql,Select,Insert Into,我正在尝试从以下位置移动旧数据: 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设置为主键。中描述了正确的语法。试试这个: INSERT INTO this_table_a

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

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设置为主键。

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

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。如果您的目标表为空,则这不会是一个问题。

对于语法而言,似乎省略了列列表以隐式表示所有

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

你不需要双倍的值位吗?如果没有,尽管一定有更好的方法,但还是尝试一下

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'));

除Mark Byers的回答外:

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

INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367
在这里,域值由我以硬编码的方式添加,以摆脱唯一约束


+1用于左连接以避免主键冲突。OP正在使用INSERT INTO。。从中选择,而不是插入。。价值观不同的功能。定义它不起作用。我有一个类似的问题,但我不能说,因为你没有说你的问题是什么!!它没有坏,只是不起作用。参见这里
    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;