在另一个问题中,我询问了为什么非空值变为NULL。但是在这个问题中,我询问了如何使空值变为NULL而不是零。
我发现丢失的浮点值始终表示为0,但不是NULL。我怎么能改变它?
以下是我创建表格和加载数据的代码。
CREATE TABLE Products(sku INTEGER, name VARCHAR(255), description TEXT,
regularPrice FLOAT,
customerReviewAverage FLOAT default NULL );
LOAD DATA LOCAL INFILE 'product.csv'
INTO TABLE Products
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(sku, name, @description, regularPrice, customerReviewAverage)
SET description = IF(@description='',NULL,@description);
这是product.csv中的数据样本。
19658847,Glanzlichter - CD,,12.99,5.0
19658856,Glanzlichter - CD,,6.99,
19658865,Glanzlichter - CD,,8.99,
1965886,Beach Boys '69 - CASSETTE,,6.99,4.5
答案 0 :(得分:3)
问题是MySQL如何解释空字段与缺少字段。 From the docs for LOAD DATA INFILE ...
如果输入行的字段太少,则缺少输入字段的表列将设置为其默认值。
空字段值的解释与缺少的字段不同。对于字符串类型,该列设置为空字符串。对于数字类型,该列设置为0.
在这种情况下,似乎MySQL认为它是为空。您可以在head
。
show warnings
然而,如果我们删除尾随的逗号,那么该字段缺少 ......
mysql> show warnings;
+---------+------+------------------------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------------------------+
| Warning | 1265 | Data truncated for column 'customerReviewAverage' at row 2 |
| Warning | 1265 | Data truncated for column 'customerReviewAverage' at row 3 |
+---------+------+------------------------------------------------------------+
2 rows in set (0.00 sec)
然后将数据设置为空。
19658847,Glanzlichter - CD,,12.99,5.0
19658856,Glanzlichter - CD,,6.99
19658865,Glanzlichter - CD,,8.99
1965886,Beach Boys '69 - CASSETTE,,6.99,4.5
对于mysql> show warnings;
+---------+------+--------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------+
| Warning | 1261 | Row 2 doesn't contain data for all columns |
| Warning | 1261 | Row 3 doesn't contain data for all columns |
+---------+------+--------------------------------------------+
mysql> select * from products;
+----------+---------------------------+-------------+--------------+-----------------------+
| sku | name | description | regularPrice | customerReviewAverage |
+----------+---------------------------+-------------+--------------+-----------------------+
| 19658847 | Glanzlichter - CD | NULL | 12.99 | 5 |
| 19658856 | Glanzlichter - CD | NULL | 6.99 | NULL |
| 19658865 | Glanzlichter - CD | NULL | 8.99 | NULL |
| 1965886 | Beach Boys '69 - CASSETTE | NULL | 6.99 | 4.5 |
+----------+---------------------------+-------------+--------------+-----------------------+
4 rows in set (0.00 sec)
和@customerReviewAverage
做同样的事情在MySQL 5.7中为我工作。
@description