在 MySQL 中通过在 WHERE 中减去日期来选择一行?
mysqlmysqli database
为此,使用 TIMESTAMPDIFF()。让我们创建一个表 −
mysql> create table demo42 −> ( −> start_date datetime −> ); Query OK, 0 rows affected (0.77 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo42 values('2020-01-10 12:30:05'); Query OK, 1 row affected (0.11 sec) mysql> insert into demo42 values('2019-02-24 10:40:45'); Query OK, 1 row affected (0.11 sec) mysql> insert into demo42 values('2020-05-12 05:45:55'); Query OK, 1 row affected (0.17 sec) mysql> insert into demo42 values('2020-05-12 05:40:55'); Query OK, 1 row affected (0.15 sec) mysql> insert into demo42 values('2020-05-12 05:42:55'); Query OK, 1 row affected (0.11 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo42;
这将产生以下输出 −
+---------------------+ | start_date | +---------------------+ | 2020-01-10 12:30:05 | | 2019-02-24 10:40:45 | | 2020-05-12 05:45:55 | | 2020-05-12 05:40:55 | | 2020-05-12 05:42:55 | +---------------------+ 5 rows in set (0.00 sec)
以下是使用 TIMESTAMPDIFF 选择一行的查询 −
mysql> select *from demo42 −> where ABS(TIMESTAMPDIFF(MINUTE,start_date, '2020−05−12 05:40:55')) < 5;
这将产生以下输出 −
+---------------------+ | start_date | +---------------------+ | 2020−05−12 05:40:55 | | 2020−05−12 05:42:55 | +---------------------+ 2 rows in set (0.00 sec)