0

我有这个:

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"),我不介意几分钟或几小时,等等,你能帮帮我吗?我该怎么做?

谢谢

4

1 回答 1

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。

于 2013-10-20T11:43:10.310 回答