如何在MySQL中将DATETIME转换为DATE?
要将DATETIME转换为MySQL中的DATE,请使用CAST()
函数。语法如下-
select cast(yourColumnName as Date) as anyVariableName from yourTableName;
要了解上述语法,让我们首先创建一个表-
mysql> create table ConvertDatetimeToDate−> (
−> YourDatetime datetime
−> );
借助insert命令将datetime插入表中。查询如下-
mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval 1 day));mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval -1 day));
mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval 1 year));
mysql> insert into ConvertDatetimeToDate values(date_add(now(),interval -1 year));
显示上面插入的所有记录。查询如下-
mysql> select *from ConvertDatetimeToDate;
以下是输出-
+---------------------+| YourDatetime |
+---------------------+
| 2018-11-28 16:12:50 |
| 2018-11-26 16:13:00 |
| 2019-11-27 16:13:13 |
| 2017-11-27 16:13:24 |
+---------------------+
4 rows in set (0.00 sec)
现在,您可以应用上述语法将datetime强制转换为date。查询如下-
mysql> select cast(YourDatetime as Date) as OnlyDateDemo from ConvertDatetimeToDate;
以下是输出-
+--------------+| OnlyDateDemo |
+--------------+
| 2018-11-28 |
| 2018-11-26 |
| 2019-11-27 |
| 2017-11-27 |
+--------------+
4 rows in set (0.00 sec)
以上是 如何在MySQL中将DATETIME转换为DATE? 的全部内容, 来源链接: utcz.com/z/347166.html