MySQL加载数据Infile Null和Expression

时间:2014-10-16 00:41:31

标签: mysql csv import null formula

我想从一个简单的csv文件中获取数据并将其放入MySQL表(我已经准备好了)中。有些列的值为'NULL'字符串,我可以在导入时成功将它们转换为空值。但是,我还希望通过转换公式放入非null值,我也可以成功完成。我的问题是我似乎无法同时做到这两件事。也就是说,我想从我的csv文件中的列中获取值,在导入之前将它们通过公式,然后取出'NULL'字符串并在MySQL中用空值替换它们。到目前为止我的代码是:

LOAD DATA INFILE 'C:/Users/Spencer/Desktop/WebProjects/WeatherMan/csvdata/day2/alabama_day2.csv'
INTO TABLE alabama_d
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(primary_id, station_id, @date, @precipitation, @snowfall, @maxtemp, @mintemp)
SET date = str_to_date(@date, '%m/%d/%y'),
precipitation = nullif(@precipitation, 'NULL'),
precipitation = @precipitation/100 * 2.54,
snowfall = nullif(@snowfall, 'NULL'),
snowfall = @snowfall/100 * 2.54,
maxtemp = nullif(@maxtemp, 'NULL'),
maxtemp = @maxtemp/10 * 9/5 + 32,
mintemp = nullif(@mintemp, 'NULL'),
mintemp = @mintemp/10 * 9/5 + 32;

如果我首先使用nullif,则会正确导入空值,但数据不会通过公式。如果我首先放置公式,它们可以工作,但是不会导入空值。我很困惑,我怎么能同时得到这两个。任何想法都表示赞赏。感谢。

1 个答案:

答案 0 :(得分:0)

原来我没有使用单行IF语句。现在我的代码工作了。它是:

LOAD DATA LOCAL INFILE 'C:/Users/Spencer/Desktop/WebProjects/WeatherMan/csvdata/day2/alabama_day2.csv'
INTO TABLE alabama_d
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(primary_id, station_id, @date, @precipitation, @snowfall, @maxtemp, @mintemp)
SET date = str_to_date(@date, '%m/%d/%y'),
precipitation = if(@precipitation = 'NULL', null, @precipitation/100 * 2.54),
snowfall = if(@snowfall = 'NULL', null, @snowfall/10 * 2.54),
maxtemp = if(@maxtemp = 'NULL', null, @maxtemp/10 * 9/5 + 32),
mintemp = if(@mintemp = 'NULL', null, @mintemp/10 * 9/5 + 32);