gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:18:14 26 4
gpt4 key购买 nike

我需要计算一行与字段 dateCompleted 是该行之前最后一个字段的行之间的 TIMEDIFF,然后获取值 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");

结果(按完成日期排序):

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

(在这个简单的例子中,他们自下一次以来都有一个第二次)

最佳答案

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;

关于mysql - 如何在没有子查询的情况下获取每行日期字段与最近的前一个日期行的 TIMEDIFF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com