119

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

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

4

5 回答 5

219

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

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桌子。如果您的目标表是空的,那么这将不是问题。

于 2011-03-09T22:56:42.660 回答
77

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

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
于 2011-03-09T22:57:48.900 回答
23

除了马克拜尔斯回答:

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

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

我在这里以硬编码的方式添加值以摆脱唯一约束。

于 2015-12-07T10:40:24.823 回答
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'));
于 2011-03-09T22:59:25.827 回答
0

更多示例和详细信息

    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;
于 2019-06-18T14:04:30.693 回答