Sql 更新包含groupby子句的表,同时避免使用临时表

Sql 更新包含groupby子句的表,同时避免使用临时表,sql,mysql,performance,Sql,Mysql,Performance,我有一个事务日志表,它在每次更新记录时都会更新 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的最新更新(这很有效,是吗?): 现在,如果我有另一个表,它应该用最新的事务日期进行更新,我如何在不创建临时表的情况下进行更新 以下查询不正确,但是否存在

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

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的最新更新(这很有效,是吗?):

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

以下查询不正确,但是否存在嵌套查询选项?我不想创建临时表

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
;

ID+Date上的外接程序索引应该会有所帮助,但不知道表的大小,u似乎选择了*而没有限制。。。有点效率低下,UPDATE语句错误,因为GROUP BYTHE table中缺少表别名。我正在处理的这个表返回700行,因此没有限制。所以表别名应该在更新查询中按工作分组?请你用粉笔写一个简单的问题好吗?我通常不参与复杂的查询,但临时表是我有点讨厌的东西!ID+Date上的外接程序索引应该会有所帮助,但不知道表的大小,u似乎选择了*而没有限制。。。有点效率低下,UPDATE语句错误,因为GROUP BYTHE table中缺少表别名。我正在处理的这个表返回700行,因此没有限制。所以表别名应该在更新查询中按工作分组?请你用粉笔写一个简单的问题好吗?我通常不参与复杂的查询,但临时表是我有点讨厌的东西!我尝试过这个,但它抛出了一个错误。我必须用othertable替换mytable,因为我正在用mytable中的数据更新othertable。创建表mytable(autoid integer主键auto_increment,id integer,
date
date,source varchar(3));将值(10,curdate()-1,'test'),(11,curdate()-5,'test'),(10,curdate()-3,'test')插入mytable(id,
date
,source);像mytable一样创建表othertable;在其他表(id)中插入值(10)、(11);注意几个问题1。curdate()-n可以替换为date\u add(curdate(),间隔n天)2。源代码的字符长度太小了非常感谢您的反馈,我真的很感激!成功了!(必须在查询中用othertable替换mytable)我尝试了此操作,但它抛出了一个错误。我必须用othertable替换mytable,因为我正在用mytable中的数据更新othertable。创建表mytable(autoid integer主键auto_increment,id integer,
date
date,source varchar(3));将值(10,curdate()-1,'test'),(11,curdate()-5,'test'),(10,curdate()-3,'test')插入mytable(id,
date
,source);像mytable一样创建表othertable;在其他表(id)中插入值(10)、(11);注意几个问题1。curdate()-n可以替换为date\u add(curdate(),间隔n天)2。源代码的字符长度太小了非常感谢您的反馈,我真的很感激!成功了!(必须在查询中用othertable替换mytable)
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
;