简体   繁体   中英

Mysql load data infile leaving unchanged fields

Suppose I have a MySQL table with three fields: key, value1, value2

I want to load data for two fields (key,value1) from file inserts.txt. Content of inserts.txt:

1;2
3;4

with:

LOAD DATA LOCAL INFILE 
   "inserts.txt"
REPLACE
INTO TABLE 
    `test_insert_timestamp`
FIELDS TERMINATED BY ';'

But in case of REPLACE, I want to leave the value2 unchanged.

How could I achieve this?

The REPLACE statement consists in the following algorithm:

MySQL uses the following algorithm for REPLACE (and LOAD DATA ... REPLACE):

Try to insert the new row into the table

While the insertion fails because a duplicate-key error occurs for a primary key or unique index:

  • Delete from the table the conflicting row that has the duplicate key value

  • Try again to insert the new row into the table

( https://dev.mysql.com/doc/refman/5.7/en/replace.html )

So you can't keep a value from a line which is going to be deleted.

What you want to do is emulating a "ON DUPLICATE KEY UPDATE" logic.

You can't do that within a single LOAD DATA query. What you have to do is to load your data in a temporary table first, then to make an INSERT from your temporary table to your destination table, where you will be able to use the "ON DUPLICATE KEY UPDATE" feature.

The whole process is fully detailed in the most upvoted answer of this question : MySQL LOAD DATA INFILE with ON DUPLICATE KEY UPDATE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM