MySQL LOAD DATA INFILE store line number

只谈情不闲聊 提交于 2019-12-18 09:46:30

问题


I'm using MySQL LOAD DATA INFILE to move CSV file data into a database table. I'm looking for a way to reference the original file line number (row) in the imported record.

So that a table like this:

CREATE TABLE tableName (
  uniqueId INT UNSIGNED NOT NULL PRIMARY_KEY,
  import_file VARCHAR(100),
  import_line INT,
  import_date = DATETIME,
  fieldA VARCHAR(100),
  fieldB VARCHAR(100),
  fieldC VARCHAR(100)
);

Where import_file,import_line and import data are meta data relevant to the specific file import. fieldA, fieldB and fieldC represent the actual data in the file.

Would be updated by a query like this:

LOAD DATA INFILE '$file' 
REPLACE
INTO TABLE '$tableName' 
FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
LINES TERMINATES BY '\n'
IGNORE 1 LINES # first row is column headers
(fieldA,fieldB,fieldC)
SET import_date = now(), 
import_file = '" . addslashes($file) . "', 
import_line = '???';

Is there a variable I can set 'import_line' to?

Thanks,

-M


回答1:


You can do that by setting a user variable first, and increment this variable in your SET clause, i.e.

SET @a:=0;                                       -- initialize the line count
LOAD DATA INFILE 'c:/tools/import.csv'           -- my test import 
REPLACE
INTO TABLE tableName 
FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES # first row is column headers
(fieldA,fieldB,fieldC)
SET import_date = now(), 
import_file = 'import.csv',               
import_line = @a:=@a+1;                          -- save the incremented line count


来源:https://stackoverflow.com/questions/23569704/mysql-load-data-infile-store-line-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!