MySQL LOAD DATA INFILE with ON DUPLICATE KEY UPDATE

时间秒杀一切 提交于 2019-11-26 01:53:29

问题


For loading huge amounts of data into MySQL, LOAD DATA INFILE is by far the fastest option. Unfortunately, while this can be used in a way INSERT IGNORE or REPLACE works, ON DUPLICATE KEY UPDATE is not currently supported.

However, ON DUPLICATE KEY UPDATE has advantages over REPLACE. The latter does a delete and an insert when a duplicate exists. This brings overhead for key management. Also, autoincrement ids will not stay the same on a replace.

How can ON DUPLICATE KEY UPDATE be emulated when using LOAD DATA INFILE?


回答1:


These steps can be used to emulate this functionality:

1) Create a new temporary table.

CREATE TEMPORARY TABLE temporary_table LIKE target_table;

2) Optionally, drop all indices from the temporary table to speed things up.

SHOW INDEX FROM temporary_table;
DROP INDEX `PRIMARY` ON temporary_table;
DROP INDEX `some_other_index` ON temporary_table;

3) Load the CSV into the temporary table

LOAD DATA INFILE 'your_file.csv'
INTO TABLE temporary_table
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(field1, field2);

4) Copy the data using ON DUPLICATE KEY UPDATE

SHOW COLUMNS FROM target_table;
INSERT INTO target_table
SELECT * FROM temporary_table
ON DUPLICATE KEY UPDATE field1 = VALUES(field1), field2 = VALUES(field2);

5) Remove the temporary table

DROP TEMPORARY TABLE temporary_table;

Using SHOW INDEX FROM and SHOW COLUMNS FROM this process can be automated for any given table.




回答2:


we can replace first (two steps) with below single query in the procedure shared by (Jan).

1) and 2) we can create new table with same reference structure and without any indexes.

CREATE TEMPORARY TABLE temporary_table SELECT * FROM target_table WHERE 1=0;

Instead of..

1) Create a new temporary table.

CREATE TEMPORARY TABLE temporary_table LIKE target_table;

2) Optionally, drop all indices from the temporary table to speed things up.

SHOW INDEX FROM temporary_table; DROP INDEX PRIMARY ON temporary_table; DROP INDEX some_other_index ON temporary_table;



来源:https://stackoverflow.com/questions/15271202/mysql-load-data-infile-with-on-duplicate-key-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!