从varchar转换为datetime并在MySQL中比较?
为此,您可以使用STR_TO_DATE()函数。让我们先创建一个表 –
mysql> create table DemoTable1565
-> (
-> ArrivalDatetime varchar(40)
-> );
Query OK, 0 rows affected (0.82 sec)
使用insert命令将一些记录插入表中 –
mysql> insert into DemoTable1565 values('10/01/2019 21:29:35');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1565 values('10/13/2019 4:56:00');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1565 values('10/13/2018 12:40:46');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1565 values('10/13/2019 21:30:00');
Query OK, 1 row affected (0.58 sec)
使用select语句显示表中的所有记录 –
mysql> select * from DemoTable1565;
这将产生以下输出 –
+---------------------+
| ArrivalDatetime |
+---------------------+
| 10/01/2019 21:29:35 |
| 10/13/2019 4:56:00 |
| 10/13/2018 12:40:46 |
| 10/13/2019 21:30:00 |
+---------------------+
4 rows in set (0.00 sec)
当前日期如下 –
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2019-10-13 21:34:14 |
+---------------------+
1 row in set (0.00 sec)
这是一个将varchar转换为datetime并比较的查询 –
mysql> select * from DemoTable1565 where str_to_date(ArrivalDatetime,'%m/%d/%Y')=curdate();
这将产生以下输出 –
+---------------------+
| ArrivalDatetime |
+---------------------+
| 10/13/2019 4:56:00 |
| 10/13/2019 21:30:00 |
+---------------------+
2 rows in set, 4 warnings (0.03 sec)
阅读更多:MySQL 教程