单个表中两个连续行中的时间戳之间的差异

时间:2014-10-09 09:47:23

标签: mysql sql

我想要来自两个连续的波纹管表行的时间戳与单个查询之间的时间差: enter image description here

我尝试过这个查询但效率非常低并且服务器超时...

SELECT t1.t_id                                           AS id1, 
       t2.t_id                                           AS id2, 
       t1.timestamp                                      AS timestamp1, 
       t2.timestamp                                      AS timestamp2, 
       Timestampdiff(second, t1.timestamp, t2.timestamp) AS diff 
FROM   (SELECT * 
        FROM   `track`) AS t1, 
       (SELECT * 
        FROM   `track` 
        WHERE  `t_id` != (SELECT `t_id` 
                          FROM   `track` 
                          LIMIT  1)) AS t2 
WHERE  ( t1.t_id - 1 ) = t2.t_id 

2 个答案:

答案 0 :(得分:2)

加入桌子,就像这样(没试过,但你明白了)

SELECT t1.t_id AS id1, 
   t2.t_id AS id2, 
   t1.timestamp AS timestamp1, 
   t2.timestamp AS timestamp2, 
   Timestampdiff(second, t1.timestamp, t2.timestamp) AS diff
FROM track AS t1
JOIN track AS t2 ON (t2.t_id = t1.t_id - 1)

答案 1 :(得分:0)

 SELECT t1.t_id                                           AS id1, 
       t2.t_id                                           AS id2, 
       t1.timestamp                                      AS timestamp1, 
       t2.timestamp                                      AS timestamp2, 
       Timestampdiff(second, t1.timestamp, t2.timestamp) AS diff 
FROM   (SELECT * 
        FROM   `track`) AS t1 Join
       (SELECT * 
        FROM   `track`) AS t2  on ( t1.t_id - 1 ) = t2.t_id  
WHERE  ( t1.t_id - 1 ) = t2.t_id