SQL |计算2行之间的时差

时间:2017-11-08 21:22:15

标签: mysql timestamp

我正在寻找一种方法来获取时间戳打开的第一行和下一行之间的时间戳。该表的想法是记录灯的开启时间。

我目前的布局是......

| id | light_id | timestamp         | log_type_id |
___________________________________________________
|  1 |        1 | current_timestamp |           1 |
|  2 |        4 | current_timestamp |           1 |
|  3 |        1 | current_timestamp |           2 |
|  4 |        1 | current_timestamp |           1 |

所以这里的想法是我能够计算ID 1和3之间的时间,然后是4和下一个带有相同light_id的时间。我不知道这是否是进行此类记录的最佳方式,如果人们有更好的解决方案,我愿意接受意见:)。

log_type_id 1 = on log_type_id 2 = off

1 个答案:

答案 0 :(得分:1)

Yes that's a good way to do it, but in MySQL you'll need to wait for MySQL 8.0 for the lead() and lag() analytic functions, though it's still doable without access to analytic functions.

Here are two examples of doing it the old school way, the first is more traditional:

select t1.id, t1.light_id, t1.timestamp, t1.log_type_id
     , l1.timestamp Prior_Timstamp
     , timestampdiff(second, l1.timestamp, t1.timestamp) minutes
  from YourData t1
  left join YourData l1
    on l1.id = (select max(id) from YourData m1 
                 where m1.id < t1.id
                   and m1.light_id = t1.light_id);

And this second uses the LIMIT/OFFSET clauses which can allow you to look further back by increasing the offset:

select t1.id, t1.light_id, t1.timestamp, t1.log_type_id
     , l1.timestamp Prior_Timestamp
     , timestampdiff(second, l1.timestamp, t1.timestamp) minutes
  from YourData t1
  left join YourData l1
    on l1.id = (select id from YourData m1 
                 where m1.id < t1.id
                   and m1.light_id = t1.light_id
                 order by id desc limit 1 offset 0);

To look forward (lead) just change inequality from < to >, and the aggregate in the first query from max to min or the order by from desc to asc in the second query.

Here's a SQL Fiddle demonstrating the code (unburied from comments at @Strawberry's request).