如何在 MySQL 中查找两个 datetime 值之间的差值?
若要查找两个 datetime 值之间的差值,可以使用 TIMESTAMPDIFF()。我们先创建一个表格 −
mysql> create table DemoTable -> ( -> DueDatetime1 datetime, -> DueDatetime2 datetime -> ); Query OK, 0 rows affected (0.86 sec)
使用 insert 命令在表格中插入一些记录 −
mysql> insert into DemoTable values('2019-10-26 19:49:00','2019-10-26 17:49:00'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('2019-10-26 08:00:00','2019-10-26 13:00:00'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2019-10-26 06:50:00','2019-10-26 12:50:00'); Query OK, 1 row affected (0.68 sec)
使用 select 语句显示表格中的所有记录 −
mysql> select *from DemoTable;
这将生成以下输出 −
+---------------------+---------------------+ | DueDatetime1 | DueDatetime2 | +---------------------+---------------------+ | 2019-10-26 19:49:00 | 2019-10-26 17:49:00 | | 2019-10-26 08:00:00 | 2019-10-26 13:00:00 | | 2019-10-26 06:50:00 | 2019-10-26 12:50:00 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
以下是实现 timestampdiff() 和查找两个日期之间差值的查询 −
mysql> select abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) from DemoTable;
这将生成以下输出 −
+------------------------------------------------------+ | abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) | +------------------------------------------------------+ | 120 | | 300 | | 360 | +------------------------------------------------------+ 3 rows in set (0.00 sec)
广告