我的桌子看起来像这样:
id entry_date
1 21/12/2020 15:00
1 21/12/2020 17:00
1 21/12/2020 19:00
2 24/12/2020 00:00
2 24/12/2020 12:00
我有一个ID连接到datestamps的列表。我可以设法计算出它们的最新条目与第一个条目之间的差异,如下所示:
SELECT id, TIMESTAMPDIFF(hour, MIN(entry_date), MAX(entry_date))
FROM mytable
GROUP BY id;
但是,我不确定如何更新表以反映这些计算。我想要的是以下内容:
id entry_date time_difference
1 21/12/2020 15:00 4
1 21/12/2020 17:00 4
1 21/12/2020 19:00 4
2 24/12/2020 00:00 12
2 24/12/2020 12:00 12
在MySQL中,您可以自我加入:
update mytable t
inner join (
select id,
timestampdiff(hour, min(entry_date), max(entry_date)) as time_difference
from mytable
group by id
) t1 on t1.id = t.id
set t.time_difference = t1.time_difference
我不一定建议存储此派生的信息,因为很难使其保持最新状态。相反,您可以创建一个视图。如果您正在运行MySQL 8.0:
create view myview as
select t.*,
timestampdiff(
hour,
min(entry_date) over(partition by id),
max(entry_date) over(partition by id)
) as timedifference
from mytable t
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句