在MySQL中从天,月,年字段创建日期?
您可以使用MySQL中内置的函数STR_TO_DATE()。 语法如下 –
SELECT
STR_TO_DATE(CONCAT(yourYearColumName,'-',LPAD(yourMonthColumName,2,'00'),'-',LPAD(yourDayColumName,2,'00')), '%Y-%m-%d') as anyVariableName from yourTableName;
为了理解上面的语法,让我们创建一个表。 创建表的查询语句如下 –
mysql> create table DateCreateDemo
−> (
−> `Day` varchar(2),
−> `Month` varchar(2),
−> `Year` varchar(4)
−> );
Query OK, 0 rows affected (1.68 sec)
使用insert命令为所有字段插入值。查询语句如下 –
mysql > insert into DateCreateDemo values('15','12','2018');
Query OK, 1 row affected (0.09 sec)
mysql > insert into DateCreateDemo values('10','11','2016');
Query OK, 1 row affected (0.37 sec)
mysql > insert into DateCreateDemo values('12','6','2017');
Query OK, 1 row affected (0.12 sec)
mysql > insert into DateCreateDemo values('9','8','2019');
Query OK, 1 row affected (0.17 sec)
mysql > insert into DateCreateDemo values('10','5','2020');
Query OK, 1 row affected (0.09 sec)
使用select语句显示表中的所有记录。查询语句如下 –
mysql > select *from DateCreateDemo;
以下是输出 –
+------+-------+------+
| Day | Month | Year |
+------+-------+------+
| 15 | 12 | 2018 |
| 10 | 11 | 2016 |
| 12 | 6 | 2017 |
| 9 | 8 | 2019 |
| 10 | 5 | 2020 |
+------+-------+------+
5 rows in set (0.00 sec)
使用上面的三个字段(’Day’,’Month’和’Year’)创建一个日期。查询语句如下 –
mysql > select
−> STR_TO_DATE(CONCAT(Year,'-',LPAD(Month,2,'00'),'-',LPAD(day,2,'00')), '%Y-%m-%d') as DateDemo from DateCreateDemo;
以下是输出结果 –
+------------+
| DateDemo |
+------------+
| 2018-12-15 |
| 2016-11-10 |
| 2017-06-12 |
| 2019-08-09 |
| 2020-05-10 |
+------------+
5 rows in set (0.06 sec)
阅读更多:MySQL 教程