我正在使用描述一组92种医学出版物(名称,日期,出版物,引文,来源,摘要)的表格。
在原始电子表格中,我将date_published中的值写为YYYY-MM-DD。然而,有些出版物当天缺席了 - 他们只有MM和YYYY。为了使每列的字符数字保持一致,我用00代替了缺失的一天(即:2014-09-00)。
对于DATE数据类型中的00,Mysql没有问题,并拒绝正确导入我的csv。因此,我将该列的数据类型更改为VARCHAR,然后将所有内容完美导入。
我想将date_published列中的所有内容从VARCHAR转换为DATE。如何让mysql将00日视为空,但仍能正确解释月份和年份?
编辑:有些出版物指明了它们发布的日期,但大多数出版物没有。如果他们这样做,我需要记录它。如果他们不能弥补一天(比如用01替换00使其成为有效的YYYY-MM-DD条目)。这是一个学术网站,他们对研究的发布日期非常特别。
答案 0 :(得分:1)
您可以使用以下导入替换0 direct:
LOAD DATA INFILE 'my.csv'
INTO TABLE TABLE_NAME
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(id, column2, column3, @mydate) -- read one of the field to variable
SET mydate = STR_TO_DATE(CONCAT(SUBSTRING_INDEX(@mydate, '-', 2),'-',
GREATEST(SUBSTRING_INDEX(@mydate, '-', -1),1)), '%Y-%m-%e');
<强>样品强>
csv
$ cat my.csv
1,foo,'bar,2017-01-00
2,foo2,'bar2,2016-04-12
3,foo,'bar,2015-08-00
导入
mysql> LOAD DATA INFILE 'my.csv'
-> INTO TABLE TABLE_NAME
-> FIELDS TERMINATED BY ','
-> LINES TERMINATED BY '\n'
-> (id, column2, column3, @mydate) -- read one of the field to variable
-> SET mydate = STR_TO_DATE(CONCAT(SUBSTRING_INDEX(@mydate, '-', 2),'-',
-> GREATEST(SUBSTRING_INDEX(@mydate, '-', -1),1)), '%Y-%m-%e');
Query OK, 3 rows affected (0,00 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT * FROM table_name;
+----+---------+---------+---------------------+
| id | column2 | column3 | mydate |
+----+---------+---------+---------------------+
| 1 | foo | 'bar | 2017-01-01 00:00:00 |
| 2 | foo2 | 'bar2 | 2016-04-12 00:00:00 |
| 3 | foo | 'bar | 2015-08-01 00:00:00 |
+----+---------+---------+---------------------+
3 rows in set (0,00 sec)
mysql>
带有额外列的样本2
mysql> SELECT * FROM table_name;
Empty set (0,00 sec)
mysql> LOAD DATA INFILE 'my.csv'
-> INTO TABLE TABLE_NAME
-> FIELDS TERMINATED BY ','
-> LINES TERMINATED BY '\n'
-> (id, column2, column3, @mydate) -- read one of the field to variable
-> SET haveDay = IF(SUBSTRING_INDEX(@mydate, '-', -1) = 0 , 0 ,1),
->
-> mydate = STR_TO_DATE(CONCAT(SUBSTRING_INDEX(@mydate, '-', 2),'-',
-> GREATEST(SUBSTRING_INDEX(@mydate, '-', -1),1)), '%Y-%m-%e');
Query OK, 3 rows affected (0,01 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT * FROM table_name;
+----+---------+---------+---------------------+---------+
| id | column2 | column3 | mydate | haveDay |
+----+---------+---------+---------------------+---------+
| 1 | foo | 'bar | 2017-01-01 00:00:00 | 0 |
| 2 | foo2 | 'bar2 | 2016-04-12 00:00:00 | 1 |
| 3 | foo | 'bar | 2015-08-01 00:00:00 | 0 |
+----+---------+---------+---------------------+---------+
3 rows in set (0,00 sec)
mysql>
答案 1 :(得分:0)
MySQL不会像这样正确地解释日期,而是用01代替00。 例; 2014年9月1日