在 MySQL 中根据日、月、年字段创建日期?
mysqlmysqli database
您可以使用 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)