INSERT INTO ...选择所有MySQL列

时间:2011-03-09 22:54:37

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

5 个答案:

答案 0 :(得分:206)

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在原始表中。如果你的目标表是空的,那么这不会是一个问题。

答案 1 :(得分:62)

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

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

答案 2 :(得分:20)

除了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

此处值由我以硬编码方式添加,以摆脱唯一约束。

答案 3 :(得分: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'));

答案 4 :(得分:0)

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;
相关问题