如何获取每行的日期字段的TIMEDIFF与最近的前一个日期行没有子查询?

时间:2016-05-08 21:06:53

标签: mysql sql

我需要计算一行和一行之间的TIMEDIFF,其中dateCompleted是该字段之前的最后一行,然后将值设为timeSinceLast

我可以像子查询一样轻松地做到这一点,但它很慢。 (比表中只有行的直接查询慢大约12-15倍)。

#Very slow
Select a.*, TIMDIFF(a.dateCompleted, (SELECT a2.dateCompleted FROM action a2 WHERE a2.dateCompleted < a.dateCompleted ORDER BY a2.dateCompleted DESC LIMIT 1)) as timeSinceLast
FROM action a;

我尝试将其作为自己的加入,但无法弄清楚如何完成这项工作,因为我不知道如何在联接表上执行LIMIT 1而不是查询作为一个整体。

#How limit the join table only?
SELECT a.*, TIMEDIFF(a.dateCompleted, a2.dateCompleted)
FROM action a
LEFT JOIN action a2 on a2.dateCompleted < a.dateCompleted 
LIMIT 1;

这在MySQL中是否可行?

编辑:架构和数据

http://sqlfiddle.com/#!9/03b5c/3

create table Actions
( 
   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
   dateCompleted datetime not null
);


#Notice, they can come out of order.
#   The third one would affect the first one in my query as
#   it's the first completed date right after the first

insert into Actions (dateCompleted)
values ("2016-05-06 12:11:01");

insert into Actions (dateCompleted)
values ("2016-05-06 12:11:03");

insert into Actions (dateCompleted)
values ("2016-05-06 12:11:02");

insert into Actions (dateCompleted)
values ("2016-05-06 12:11:05");

insert into Actions (dateCompleted)
values ("2016-05-06 12:11:04");

结果(按dateCompleted排序):

id  dateCompleted          timeSinceLast
 1, "2016-05-06 12:11:01", null
 3, "2016-05-06 12:11:02", 1
 2, "2016-05-06 12:11:03", 1
 5, "2016-05-06 12:11:04", 1
 4, "2016-05-06 12:11:05", 1

(在这个简单的例子中,他们从下一次开始都有一秒钟的时间)

1 个答案:

答案 0 :(得分:2)

SELECT x.*
     , MIN(TIMEDIFF(x.datecompleted,y.datecompleted)) 
  FROM actions x 
  LEFT 
  JOIN actions y 
    ON y.datecompleted < x.datecompleted 
 GROUP 
    BY x.id 
 ORDER 
    BY x.datecompleted;

......或更快......

SELECT x.*
     , TIMEDIFF(datecompleted,@prev)
     , @prev:=datecompleted 
  FROM actions x
     , (SELECT @prev:=null) vars 
 ORDER 
    BY datecompleted;