mysql查询相邻数据时间差

来源:互联网 发布:对网络课程的认识 编辑:程序博客网 时间:2024/06/10 06:15
select A.user_id,A.punch_time,TIMESTAMPDIFF(SECOND,A.punch_time,B.punch_time) sub_seconds
from(
    select a.*,(@i := @i + 1) as ord_num from t_punch_cade a,(select @i := 1) d order by user_id,punch_time
) as A LEFT JOIN (
    select a.*,(@j := @j + 1) as ord_num from t_punch_cade a,(select @j := 0) c order by user_id,punch_time

)as B on A.ord_num=B.ord_num and A.user_id=B.user_id



比如排序之后我们想计算两条相邻记录的时间差,因为mysql没有窗口函数所以要么模拟窗口函数要么使用表自关联

我们可以使用增加一个错位序号的字段,然后使用序号条件关联




原文地址:http://blog.csdn.net/tangpengh/article/details/53171313