我試圖從移動舊數據:INSERT INTO ... SELECT所有的MySQL列
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 ... SELECT所有的MySQL列
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
集作爲主鍵。
正確的語法在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。如果你的目標表是空的,那麼這不會是一個問題。
有關語法,它看起來像這樣(留出列清單,隱含的意思是「所有」)
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
用於左連接以避免主鍵衝突。 – 2014-07-24 16:00:45
你不需要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'。不同的功能。 – 2015-07-30 15:59:12
加成馬克拜爾斯答案:
有時你也想插入硬編碼其他細節有可能是唯一的約束失效等,所以使用在這種情況下,你重寫列的一些值。
INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367
這裏域值由我我硬編碼的方式加入到獲得從擺脫獨特的約束。
定義「它不起作用」。我有什麼可能是類似的問題,但我不能說,因爲你沒有說你的問題是什麼! – 2015-07-30 15:59:53
它沒有壞,它只是不起作用。 – 2017-09-08 20:52:10
另請參閱這裏[https://stackoverflow.com/questions/3709560/joining-three-tables-using-mysql](https://stackoverflow.com/questions/3709560/joining-three-tables-using-mysql) – 2017-10-11 23:14:00