我正在尝试将数据导入到表中。目前我正在努力
LOAD DATA local INFILE "C:/PRINT DAILY DOC_CommaDelimited.txt"
into table daily_doc_report_full
fields terminated by ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 5 LINES;
导入数据是这样的
" 1","SALES DEPT SALES "," 0"," -285,723","
导入时,第四个字段中的逗号会扰乱数据的导入方式。
数据应该是这样的
| Line| Description | today | Month_to_date|
| 1| Sales Dept Sales | 0.00| -285,723.00|
数据被截断并显示
| Line| Description | today | Month_to_date|
| 1| Sales Dept Sales | 0.00| -285.00|
我尝试了对加载数据本地文件查询进行各种更改,例如从
OPTIONALLY
中删除 ENCLOSED BY '"'
,但我就是无法让它按预期工作。我使用的是 MYSQL 8.0
MySQL 不理解以逗号作为千位分隔符格式的数字。如果您尝试将包含逗号的字符串转换为数字,它会忽略从逗号到结尾的任何字符。
这与 LOAD DATA INFILE 或括起来的引号无关。我们可以用一个简单的 CAST() 表达式来演示同样的问题:
mysql> select cast('-285,723' as decimal);
+-----------------------------+
| cast('-285,723' as decimal) |
+-----------------------------+
| -285 |
+-----------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> select cast('-285723' as decimal);
+----------------------------+
| cast('-285723' as decimal) |
+----------------------------+
| -285723 |
+----------------------------+
您可以使用 LOAD DATA INFILE 解决此问题,方法是首先将字符串复制到用户变量,然后从用户变量中删除逗号。
我用 MySQL 8.3 对此进行了测试:
mysql> LOAD DATA local INFILE 'c.csv' into table mytable
fields terminated by ','
OPTIONALLY ENCLOSED BY '"'
(line, description, @today, @month_to_date)
set today = replace(@today, ',', ''),
month_to_date = replace(@month_to_date, ',', '');
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> select * from mytable;
+------+-------------------------------+-------+---------------+
| line | description | today | month_to_date |
+------+-------------------------------+-------+---------------+
| 1 | SALES DEPT SALES | 0.00 | -285723.00 |
+------+-------------------------------+-------+---------------+