如何从 datetime 列中仅选择 MySQL 日期?
mysqlmysqli database
为此使用 DATE_FORMAT。让我们首先创建一个表 −
mysql> create table DemoTable ( ShippingDate varchar(200) ); Query OK, 0 rows affected (0.25 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('04:58 PM 10/31/2018'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('02:30 AM 01/01/2019'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values('12:01 AM 05/03/2019'); Query OK, 1 row affected (0.06 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+---------------------+ | ShippingDate | +---------------------+ | 04:58 PM 10/31/2018 | | 02:30 AM 01/01/2019 | | 12:01 AM 05/03/2019 | +---------------------+ 3 rows in set (0.00 sec)
以下是从日期时间列中仅选择日期的查询 −
mysql> SELECT DATE_FORMAT(STR_TO_DATE(ShippingDate, '%h:%i %p %m/%d/%Y'), '%m/%d/%Y') from DemoTable;
这将产生以下仅显示日期的输出 −
+-------------------------------------------------------------------------+ | DATE_FORMAT(STR_TO_DATE(ShippingDate, '%h:%i %p %m/%d/%Y'), '%m/%d/%Y') | +-------------------------------------------------------------------------+ | 10/31/2018 | | 01/01/2019 | | 05/03/2019 | +-------------------------------------------------------------------------+ 3 rows in set (0.00 sec)