2011-10-11 61 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