1

I want the time difference between timestamps from two consecutive rows of bellow table with single query : enter image description here

I tried this query but which is very inefficient and giving server timeout...

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 
1
  • is there a chance that you'd have a gap in your t_id field? :D
    – Jaak Kütt
    Oct 9, 2014 at 9:59

2 Answers 2

2

Join the table with itself, like this (haven't tried, but you get the idea)

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)
2
  • 1
    table don not have primary key. you considered t_id as auto increment which is not the case
    – Ravindra
    Oct 9, 2014 at 10:14
  • First, a table should always have a primary key. Secondly you'll need at least an index on t_id so the join/where etc would have reasonable performance. So make t_id the PRIMARY key and maybe even your original solution will run fast enough ...
    – fejese
    Oct 9, 2014 at 10:17
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  
1
  • table don not have primary key. you considered t_id as auto increment which is not the case...
    – Ravindra
    Oct 9, 2014 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.