Question

EDIT: To clarify there are many users and each user has many records, this is a log table of user activities,

how to find the timestamp difference every record and subsequent record that satisfies some condition ,

for example assuming the table is something like this

| id |u_id| .. | timestamp          | 
|----|----|----|--------------------|
| 50 | 1  | .. | 2014-04-22 15:35:44|
| 90 | 2  | .. | 2014-04-22 13:35:44|
| .. | .. | .. | .....              |

How do I find the time difference between every record and the next record for only one user id ?

Was it helpful?

Solution

Assuming that you want to do this for all users, the easiest way is to use variables:

select t.*,
       if(u_id = @u_id, timediff(`timestamp`, @timestamp), NULL) as diff,
       @timestamp := `timestamp`, @u_id := u_id
from table t cross join
     (select @timestamp := 0, @u_id := 0) var
order by u_id, timestamp;

It is important that you explicitly order the records to be sure that the processing occurs in sequential order.

OTHER TIPS

Try

select timediff(`timestamp`, @lasttime),
       @lasttime := `timestamp`
from your_table
cross join (select @lasttime := 0) d
where u_id = 1
order by id

There are a couple of ways you can do this, the first would be to use a correlated subquery:

SELECT  T.id,
        T.u_id,
        timestamp,
        (   SELECT  T2.timestamp
            FROM    T AS T2
            WHERE   T2.u_id = T.u_id
            AND     T2.timestamp > T.timestamp
            ORDER BY T2.Timestamp
            LIMIT 1
        ) AS NextTimeStamp
FROM    T;

Or you could do this using JOIN.

SELECT  T.id,
        T.u_id,
        T.timestamp,
        T2.timestamp AS NextTimeStamp
FROM    T
        LEFT JOIN T AS T2
            ON T2.u_id = T.u_id
            AND T2.timestamp > T.timestamp
        LEFT JOIN T AS T3
            ON T3.u_id = T.u_id
            AND T3.timestamp > T.timestamp
            AND T3.timestamp < T2.timestamp
WHERE   T3.id IS NULL;

Which one is best will depend on your actual requirements, amount of data, and indexes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top