为了获得两个时间戳之间的差异(以秒为单位),请使用两个内置函数TIME_TO_SEC()和TIMEDIFF()
MySQL。语法如下-
select time_to_sec(timediff(yourCoulnName1,yourCoulnName2)) as anyVariableName from yourTableName;
为了理解上述概念,让我们首先创建一个表。查询创建表。
mysql> create table TimeToSecond −> ( −> MyTime timestamp, −> YourTime timestamp −> );
现在,您可以在表中插入一些日期时间值。查询如下-
mysql> insert into TimeToSecond values('2016-05-10 10:02:00','2016-05-10 10:00:00'); mysql> insert into TimeToSecond values('2016-05-10 10:06:00','2016-05-10 10:03:00'); mysql> insert into TimeToSecond values('2018-05-10 11:00:00','2018-05-10 10:00:00');
插入后,您可以借助select语句检查表中存在多少条记录。显示所有记录的查询如下-
mysql> select *from TimeToSecond;
以下是输出-
+---------------------+---------------------+ | MyTime | YourTime | +---------------------+---------------------+ | 2016-05-10 10:02:00 | 2016-05-10 10:00:00 | | 2016-05-10 10:06:00 | 2016-05-10 10:03:00 | | 2018-05-10 11:00:00 | 2018-05-10 10:00:00 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
现在,使用上面讨论的语法,以秒为单位获得两个时间戳之间的差异。查询如下-
mysql> select time_to_sec(timediff(MyTime,YourTime)) as DifferenceInSeconds from TimeToSecond;
以下是输出-
+---------------------+ | DifferenceInSeconds | +---------------------+ | 120 | | 180 | | 3600 | +---------------------+ 3 rows in set (0.00 sec)