同一个表上的记录之间的日期差异

时间:2013-10-20 11:24:28

标签: mysql sql date sliding-window

我有这个:

SELECT 
  journals.id,
  issues.created_on,
  user_id,
  journalized_id,
  journals.created_on
FROM journals, issues 
where issues.id=journals.journalized_id and journalized_id=23363

显示下一个结果:

 id    user_id  journalized_id       created_on  
-----  -------  --------------  -------------------
77996      182           23363  2013-10-07 13:41:45
77998      182           23363  2013-10-07 13:43:08
78000      174           23363  2013-10-07 13:54:26
78137      174           23363  2013-10-08 15:38:43
78269      167           23363  2013-10-09 17:14:26
78328      182           23363  2013-10-10 12:35:02
78442      167           23363  2013-10-11 18:06:13

我希望获得一个“created_on”记录与前一个记录或同一个journalized_id的下一个记录之间的时差。

例如:新行的第一条记录为0(“2013-10-07 13:41:45” - “2013-10-07 13:41:45”),但接下来会是(“2013 -10-07 13:43:08“ - ”2013-10-07 13:41:45“),我不介意几分钟或几小时,等下一个,你能帮助我吗?我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:0)

我没有相应的表格,但已检查此语法:

更新使用之前的日期&的MySQL :: TIMEDIFF():

SELECT journals.id, user_id, journalized_id
  , TIMEDIFF(journals.created_on,
    IFNULL(
      (SELECT MAX(t.created_on)
       FROM journals t
       INNER JOIN issues ON t.journalized_id=issues.id
       WHERE t.journalized_id=23363 AND t.id<journals.id),
    journals.created_on)
  )
FROM journals
INNER JOIN issues ON journals.journalized_id=issues.id
WHERE journalized_id=23363;

这可能会加速使用变量@dprev = previous date:

SET @dprev := 0;
SELECT journals.id, user_id, journalized_id
  , TIMEDIFF(journals.created_on,
    IF(@dprev, @dprev, journals.created_on))
  , @dprev := journals.created_on
FROM journals
INNER JOIN issues ON journals.journalized_id=issues.id
WHERE journalized_id=23363;

?不方便的是还显示了第三列@dprev。