MySQL中两个时间戳相差多少秒?
您可以使用MySQL的内置函数UNIX_TIMESTAMP()获取时间戳以及两个时间戳之间的差值。语法如下:
SELECT UNIX_TIMESTAMP(yourColumnName1) - UNIX_TIMESTAMP(yourColumnName2) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询:
mysql> create table DifferenceInSeconds −> ( −> FirstTimestamp TIMESTAMP, −> SecondTimestamp TIMESTAMP −> ); Query OK, 0 rows affected (0.93 sec)
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into DifferenceInSeconds values('2012-12-12 13:16:55','2012-12-12 13:13:55'); Query OK, 1 row affected (0.31 sec) mysql> insert into DifferenceInSeconds values('2014-10-11 12:15:50','2014-10-11 12:13:50'); Query OK, 1 row affected (0.19 sec) mysql> insert into DifferenceInSeconds values('2018-12-14 13:30:53','2018-12-14 13:27:53'); Query OK, 1 row affected (0.21 sec)
现在使用select语句显示表中的所有记录。查询如下:
mysql> select *from DifferenceInSeconds;
以下是输出:
+---------------------+---------------------+ | FirstTimestamp | SecondTimestamp | +---------------------+---------------------+ | 2012-12-12 13:16:55 | 2012-12-12 13:13:55 | | 2014-10-11 12:15:50 | 2014-10-11 12:13:50 | | 2018-12-14 13:30:53 | 2018-12-14 13:27:53 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
以下是查找两个时间戳之间以秒为单位的差值的查询。查询如下:
mysql> SELECT UNIX_TIMESTAMP(FirstTimestamp) - UNIX_TIMESTAMP(SecondTimestamp) as Seconds from DifferenceInSeconds;
以下是输出:
+---------+ | Seconds | +---------+ | 180 | | 120 | | 180 | +---------+ 3 rows in set (0.00 sec)
注意 - 如果您不知道哪个时间戳更大,请使用ABS()。
语法如下:
SELECT ABS(UNIX_TIMESTAMP(yourColumnName1) - UNIX_TIMESTAMP(yourColumnName2)) as Seconds from DifferenceInSeconds;
为了检查上述语法,让我们插入第一个时间戳值较低的记录。
mysql> insert into DifferenceInSeconds values('2018-12-14 13:26:53','2018-12-14 13:31:53'); Query OK, 1 row affected (0.21 sec)
显示表中所有记录的查询。
mysql> select *from DifferenceInSeconds;
以下是输出:
+---------------------+---------------------+ | FirstTimestamp | SecondTimestamp | +---------------------+---------------------+ | 2012-12-12 13:16:55 | 2012-12-12 13:13:55 | | 2014-10-11 12:15:50 | 2014-10-11 12:13:50 | | 2018-12-14 13:30:53 | 2018-12-14 13:27:53 | | 2018-12-14 13:26:53 | 2018-12-14 13:31:53 | +---------------------+---------------------+ 4 rows in set (0.00 sec)
以下是ABS()函数的用法。查询如下:
mysql> SELECT ABS(UNIX_TIMESTAMP(FirstTimestamp) - UNIX_TIMESTAMP(SecondTimestamp)) as Seconds from DifferenceInSeconds;
以下是输出:
+---------+ | Seconds | +---------+ | 180 | | 120 | | 180 | | 300 | +---------+ 4 rows in set (0.00 sec)
注意 - 如果不使用ABS(),则上述输出将为-300秒。
广告