7

I have a MYSQL database containing a bunch of fields, many of which are configures as numerical values, either:

thickness double(7,2) DEFAULT NULL,

or

has_input tinyint(4) DEFAULT NULL,

I have to import a csv file into this table and have been using

load data local infile 'myfilepath/file.csv' into table combined fields terminated by ',' enclosed by '"' lines terminated by '\r\n';

but all numerical fields are having null values replaced by zero. This is really annoying as some fields have a legitimate value of zero and I need to be able to distinguish these from the fields with no value.

As you can see above, the field defaults are set to null and, on other advice, I've entered \N in all the blank fields in the csv to indicate null.

Nevertheless, the nulls are still being replaced with zero. Can you help?

4

2 回答 2

12

由于在导入 CSV 时处理 NULL 列的规则相当复杂,因此在 LOAD DATA INFILE 的文档中有专门的部分处理 NULL 值:http:
//dev.mysql.com/doc/refman/5.1/en/load -data.html

在您的具体情况下:

如果 FIELDS ENCLOSED BY 不为空,则将包含文字 NULL 作为其值的字段读取为 NULL 值。这与包含在 FIELDS ENCLOSED BY 字符中的单词 NULL 不同,后者被读取为字符串“NULL”。


尝试通过用单词NULL(不带引号)替换缺失值来预处理 CSV 文件。

如果您的原始 CSV 文件中有类似的内容:

0,1,2,,5

它应该像这样转换,以便 MySQL 在第 4 列中正确插入 NULL:

0,1,2,NULL,5
于 2013-08-02T10:53:02.857 回答
7

它可以在同一个句子中处理。

给定下表:

CREATE TABLE `testcsv` (
  `col0` INT(11) NOT NULL,
  `col1` VARCHAR(20) DEFAULT NULL,
  `col2` DECIMAL(5,2) DEFAULT NULL
);

和以下文件 .csv:test.csv

1,\N,0
2,"string",102.20
3,\N,
4,"string",\N
5,"string",NULL
6,"string",

跑步:

LOAD DATA INFILE 'path/test.csv' INTO TABLE `testcsv`
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
(`col0`, `col1`, @col2)
SET `col2` = IF(CHAR_LENGTH(TRIM(@col2)) = 0, NULL, @col2);

结果:

mysql> SELECT `col0`, `col1`, `col2` FROM `testcsv`;

+------+--------+--------+
| col0 |  col1  |  col2  |
+------+--------+--------+
|    1 | NULL   |   0.00 |
|    2 | string | 102.20 |
|    3 | NULL   |   NULL |
|    4 | string |   NULL |
|    5 | string |   NULL |
|    6 | string |   NULL |
+------+--------+--------+
6 ROWS IN SET (0.00 sec)
于 2013-08-02T12:24:17.630 回答