在 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)
使用上述三个字段(“日期”、“月份”和“年份”)创建日期。查询如下 −
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)
广告