mysql - 如果长于 n 时间,则获取两条记录之间的时间差

标签 mysql math

我正在寻找一种方法来获取两条记录之间的时间(可能多次),如果它们大于n时间;在我的例子中,我正在寻找大于 5 分钟的差异。

例如:

+------+---------+---------------------+
| id   | number  | created_at          |
+------+---------+---------------------+
| 1768 | 3709529 | 2017-04-06 19:13:54 |
| 1772 | 3709530 | 2017-04-06 19:14:38 |
| 1780 | 3709531 | 2017-04-06 19:16:29 |
| 1783 | 3709532 | 2017-04-06 19:17:13 |
| 1787 | 3709533 | 2017-04-06 19:18:04 |
| 1793 | 3709534 | 2017-04-06 19:18:59 |
| 1800 | 3709535 | 2017-04-06 19:20:20 | << This Would be a record with 
| 1808 | 3709536 | 2017-04-06 19:45:59 | << more then 5 min difference
| 1809 | 3709537 | 2017-04-06 19:46:59 |
| 1816 | 3709538 | 2017-04-06 19:48:17 |
| 1831 | 3709540 | 2017-04-06 19:52:05 |
| 1835 | 3709539 | 2017-04-06 19:52:53 |
| 1839 | 3709541 | 2017-04-06 19:53:36 |
| 1842 | 3709542 | 2017-04-06 19:54:07 |
| 1846 | 3709543 | 2017-04-06 19:54:52 |
| 1849 | 3709544 | 2017-04-06 19:55:25 |
| 1853 | 3709545 | 2017-04-06 19:56:13 |
| 1859 | 3709546 | 2017-04-06 19:57:09 |
| 1863 | 3709547 | 2017-04-06 19:58:01 |
| 1869 | 3709548 | 2017-04-06 19:59:23 |
+------+---------+---------------------+
20 rows in set (0.00 sec)

所以我需要基于开始和结束日期时间选择指令一些像这样的值:

3709536 | 25 (or 00:25:00)

有什么办法可以实现这一点吗?

可能有多个结果

非常感谢

最佳答案

假设时间不是那么大,可以使用timediff():

select t.*,
       timediff(created_at, prev_created_at) as time_diff
from (select t.*,
             (select t2.created_at
              from t t2
              where t2.created_at < t.created_at
              order by t2.created_at desc
              limit 1
             ) prev_created_at
      from t
     ) t
where prev_created_at < t.created_at - interval 5 minute;

关于mysql - 如果长于 n 时间,则获取两条记录之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46524456/

相关文章:

python - mysql数据库插入数据时出错

c# - 为什么不是 DbConnection 而不是 SqlConnection 或 OracleConnection?

math - 查找与虚数相邻的函数的根

javascript - 在javascript中获取最接近的笛卡尔轴对齐向量

javascript - 按顺时针方向排序点

mysql - 使用 pg :backups restore 恢复表

python - DatabaseError : Execution failed on sql, 无法将元组连接到字节

java - 将 Double 截断为小数点后两位?

如果用Excel查询,mysql select search显示时间太长

Java:使用 `Math.sin()` 时可能会丢失精度