gpt4 book ai didi

sql - 更新涉及 groupby 子句的表,同时避免使用临时表

转载 作者:行者123 更新时间:2023-11-29 00:59:42 27 4
gpt4 key购买 nike

我有一个事务日志表,每次更新记录时都会更新该表。

autoid ID Date        Source
1 1 2010-10-11 abc
2 2 2010-09-10 xyz
3 1 2010-08-03 pqr
4 1 2010-11-01 mno

我可以通过以下查询获取每个 ID 的最新更新(这很有效,是吗?):

select * from mytable group by ID order by Date desc;

现在,如果我有另一个表应该用最近的交易日期更新,我该如何在不创建临时表的情况下进行更新?

以下查询不正确,但是否有嵌套查询替代方案?我不想创建临时表。

update mytable a, othertable b
set b.date = a.date
where b.ID = a.ID group by ID order by Date desc;

ajreal 的解决方案奏效了!

update othertable,
(select b.id, max(b.`date`) as latest from mytable b group by b.id) as b
set othertable.`date` = b.latest
where othertable.id=b.id
;

最佳答案

update mytable,
(select b.id, max(b.`date`) as latest from othertable b group by b.id) as b
set mytable.`date`=b.latest
where mytable.id=b.id
;

关于sql - 更新涉及 groupby 子句的表,同时避免使用临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4138510/

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