根据计算更新列

Update columns based on calculation

我的 table 看起来像这样:

    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's 的列表连接到 datestamps。我可以设法计算出他们的最新条目和第一个条目之间的差异,如下所示:

SELECT id, TIMESTAMPDIFF(hour, MIN(entry_date), MAX(entry_date))
FROM mytable
GROUP BY id;

但是,我不确定如何 更新 我的 table 以反映这些计算。我想要的是:

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

您可以在 update 中使用 join:

update mytable t join
       (SELECT id, TIMESTAMPDIFF(hour, MIN(entry_date), MAX(entry_date)) as diff
        FROM mytable
        GROUP BY id
       ) tt
       using (id)
    set t.time_difference = tt.diff;