MySQL的两个时间戳之间的差异秒?
您可以使用MySQL的内置函数UNIX_TIMESTAMP()来获取时间戳和两个时间戳之间的差。语法如下-
SELECT UNIX_TIMESTAMP(yourColumnName1) - UNIX_TIMESTAMP(yourColumnName2) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询-
mysql> create table DifferenceInSeconds−> (
−> FirstTimestamp TIMESTAMP,
−> SecondTimestamp TIMESTAMP
−> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into DifferenceInSeconds values('2012-12-12 13:16:55','2012-12-12 13:13:55');mysql> insert into DifferenceInSeconds values('2014-10-11 12:15:50','2014-10-11 12:13:50');
mysql> insert into DifferenceInSeconds values('2018-12-14 13:30:53','2018-12-14 13:27:53');
现在,使用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');
查询以显示表中的所有记录。
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秒将是以上输出。
以上是 MySQL的两个时间戳之间的差异秒? 的全部内容, 来源链接: utcz.com/z/353451.html