CSV到Mysql导入脚本以匹配字段

时间:2011-10-11 14:46:26

标签: php mysql csv

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

示例:

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

假设第一个字段是一个ID,我希望脚本在记录不存在时插入但在ID已经存在时更新,因此John Doe将首先作为程序员插入,但随后更新为CTO。

2 个答案:

答案 0 :(得分:1)

MySQL reference manual中的LOAD DATA section

  

REPLACE和IGNORE关键字控制输入行的处理   复制唯一键值上的现有行:

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

答案 1 :(得分:0)

尝试以下内容可能对您有所帮助CSV TO MySQl

祝你好运