使用 join 和 max 更新行

Update row with join and max

我有以下两个 tables(简化架构):

score
-----
id
score

score_history
-------------
id
score_id (foreign key with score table)
score

我会定期填充 score_history table。我想更新分数 table 中的每一行,分数列基于 score_history 中的分数,关联的最大 ID 号。

例如:

score entries
+----+-------+
| id | score |
+----+-------+
| 1  | 0     |
| 2  | 0     |
+----+-------+

score_history entries
+----+----------+-------+
| id | score_id | score |
+----+----------+-------+
| 1  | 1        | 15    |
| 2  | 2        | 10    |
| 3  | 1        | 14    |
| 4  | 2        | 11    |
+----+----------+-------+

在条目 3/4 存在于 score_history 之前,我想在一个从分数 table 更新分数的请求中如下:

+----+-------+
| id | score |
+----+-------+
| 1  | 15    |
| 2  | 10    |
+----+-------+

在 score_history 中插入条目 3/4 后,我再次希望相同的请求具有我的分数 table,例如:

+----+-------+
| id | score |
+----+-------+
| 1  | 14    |
| 2  | 11    |
+----+-------+

我尝试了多种方法(例如 )但未能成功。

有什么想法吗?

UPDATE score s
SET score = 
   (SELECT score FROM score_history sh WHERE sh.score_id = s.ID  ORDER BY SH.id ASC LIMIT 1)
update score 
join score_history on score.id = score_history.score_id 
join 
(select score_id, max(id) mid
from score_history
group by score_id) t
on score_history.id = t.mid
set score.score = score_history.score 

首先获取历史记录table中每个score_id的最大值(history_id)。

然后加入id最大的历史

最后加入分数table并将分数列设置为具有最大id

的分数

如果您正在寻找更新命令,它可能是

update 
score s 
join score_history sh on sh.score_id = s.id 
join ( 
  select max(id) as max_id, score_id  from score_history group by score_id
)x on x.max_id = sh.id and x.score_id = sh.score_id 
set s.score = sh.score ;