简体   繁体   English

MySQL加载数据infile保留不变的字段

[英]Mysql load data infile leaving unchanged fields

Suppose I have a MySQL table with three fields: key, value1, value2 假设我有一个包含三个字段的MySQL表:key,value1,value2

I want to load data for two fields (key,value1) from file inserts.txt. 我想从文件inserts.txt加载两个字段(键,值1)的数据。 Content of inserts.txt: 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. 但是在替换的情况下,我想保持value2不变。

How could I achieve this? 我怎样才能做到这一点?

The REPLACE statement consists in the following algorithm: REPLACE语句包含以下算法:

MySQL uses the following algorithm for REPLACE (and LOAD DATA ... REPLACE): MySQL对REPLACE(和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 ) 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. 您想要做的是模拟“ ON DUPLICATE KEY UPDATE”逻辑。

You can't do that within a single LOAD DATA query. 您不能在单个LOAD DATA查询中执行此操作。 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. 您要做的是先将数据加载到临时表中,然后将INSERT从临时表插入到目标表中,在此表中将可以使用“ ON DUPLICATE KEY UPDATE”功能。

The whole process is fully detailed in the most upvoted answer of this question : MySQL LOAD DATA INFILE with ON DUPLICATE KEY UPDATE 整个过程在此问题的最高支持答案中有详细介绍: MySQL LOAD DATA INFILE ON ON DUPLICATE KEY UPDATE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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