使用“加载数据infile”时如何识别重复行

时间:2014-05-06 14:53:58

标签: mysql

我正在尝试将数据从csv文件加载到我的数据库中。但是,行必须是唯一,也就是说,如果所有列包含相同的数据,则行是相同的。

我现在的方法是添加一个新列,其中包含所有其他列的MD5总和。为此,我创建了一个存储过程(通过使用information_schemes.columns),该过程返回一个字符串,其中包含将获得此唯一MD5总和(uniqueIdentifier)的列以外的所有列。

现在,导入数据的代码如下所示(我希望保持灵活性,以后能够将其应用到其他文件中):

call select_all_exclude_one('vegas', 'uniqueIdentifier', @exclude_fields);

set @file_input = 'C:/MRTK_Enigma_IRD_VegaOSWP_New_Format.csv' ;
set @field_terminate = '|';
set @line_terminate = '\\n';
set @date_format = '%Y%m%d %H:%i:%s';
set @columns_input = 'deskCode, bookName, riskType, riskTypeShiftSizeInBP, productCode, currency, 
    maturity, maturityUnderlying, riskValue, currencyRiskValue, 
    issuerCategory, countryOfIssuer, ratingCategory, postDate, 
    @the_date, strike, currencyBase, indexCategory, EOL';


set @sql = concat('LOAD DATA INFILE ''', @file_input, '''

IGNORE

INTO TABLE skewrisk.vegas 
FIELDS TERMINATED BY ''', @field_terminate, ''' 
LINES TERMINATED BY ''', @line_terminate, ''' 
IGNORE 1 LINES \n(', @columns_input,

')\nset lastUpdate      = str_to_date(@the_date, ''', @date_format, '''),
uniqueIdentifier    = MD5(concat(', @exclude_fields,  '))');

select @sql;
prepare stmt from @sql;
execute stmt;

在代码的末尾,列uniqueIdentifier(标记为主键)被设置为包含除自身之外的所有列的MD5总和。

但是,运行此代码时出现以下错误:

Action: prepare stmt from @sql
Message: Error Code: 1295. This command is not supported in the prepared statement protocol yet

问题: 1)我尝试的是否有更简单的方法? 2)如果没有,怎么解决?

2 个答案:

答案 0 :(得分:0)

在所有列上定义UNIQUE约束:

ALTER TABLE skewrisk.vegas ADD UNIQUE (
  deskCode, bookName, riskType, riskTypeShiftSizeInBP, productCode, currency, 
  maturity, maturityUnderlying, riskValue, currencyRiskValue, 
  issuerCategory, countryOfIssuer, ratingCategory, postDate, 
  strike, currencyBase, indexCategory, EOL, lastUpdate
);

然后使用LOAD DATA IGNORE

  

如果指定IGNORE,则会跳过复制唯一键值上现有行的输入行。

注意:如果文件包含表的主键,则不需要这样做(因为PK必须是唯一的)。

答案 1 :(得分:-1)

我遇到了类似的问题,并将行的值连接到主键列。没有一个列值是唯一的,但是日期和几列的值的组合确保了我有一个唯一的索引值,如果有人试图再次导入这些值,它将不允许重复:

LOAD DATA LOCAL INFILE 'file' 
    INTO TABLE table_name 
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"' 
    LINES TERMINATED BY '\\r\\n' 
    (unique_id, date, col1, col2, ... ) 
    SET unique_id = CONCAT(date,col1,col2)