2011-10-11 38 views
2

是否有这样的脚本或从CSV导入数据到MySQL的方式,可以匹配第一个字段,而不是覆盖数据只会更新行中缺少的字段或值?希望我已经清楚地解释了我自己!CSV到Mysql导入脚本以匹配字段

例子:

1,john,doe,programmer 
2,jane,doe,accountant 
3,judy,doe,manager 
1,john,doe,cto 

假设第一个字段是一个ID,我希望脚本插入时,记录不存在,但是当ID已经存在,所以李四将首先把插入的更新程序员,但后来更新为CTO。

回答

1

MySQL reference manual,在LOAD DATA section

替换,而忽略关键字输入行的控制处理是 重复现有行上的唯一键值:

If you specify REPLACE, input rows replace existing rows. 
In other words, rows that have the same value for a primary key or unique index 
as an existing row. See Section 12.2.7, “REPLACE Syntax”. 

If you specify IGNORE, input rows that duplicate an existing row 
on a unique key value are skipped. If you do not specify either 
option, the behavior depends on whether the LOCAL keyword is 
specified. Without LOCAL, an error occurs when a duplicate key value 
is found, and the rest of the text file is ignored. With LOCAL, the 
default behavior is the same as if IGNORE is specified; this is 
because the server has no way to stop transmission of the file in the 
middle of the operation. 

所以我相信,如果你设置您存储的名称作为主键或唯一索引的字段,你应该能够做到:

LOAD DATA LOCAL INFILE 'file.csv' 
REPLACE INTO TABLE yourtable 
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n' 
(id, name, surname, etc); 

更新:

刚刚发现了一些关于这个问题的更多资源:

mysql duplicates with LOAD DATA INFILE

http://support.modwest.com/content/6/253/en/how-do-i-import-delimited-data-into-mysql.html

http://codeinthehole.com/archives/35-How-to-sync-a-MySQL-table-between-two-remote-databases..html