mysql update left join 更新最大值
問題:
如何使用 mysql update 語句和 left join 從多條數(shù)據(jù)中獲取最大值并更新另一個表的特定字段?
例子:
我們有 student 表:
id | name | score |
---|---|---|
1 | 小明 | NULL |
2 | 小紅 | null |
以及 score 表:
id | student_id | score |
---|---|---|
1 | 1 | 80 |
2 | 2 | 88 |
3 | 1 | 78 |
4 | 2 | 98 |
我們的目標(biāo)是更新 student 表的 score 字段為 score 表中每個 student_id 對應(yīng)的最大 score 值。
解答:
使用 left join 和子查詢可以實(shí)現(xiàn)此目的:
update student set score=(select max(score) from score where score.student_id=student.id)
解釋:
- left join 將 student 表與 score 表連接,其中 student.id 與 score.student_id 匹配。
- 子查詢 max(score) 獲取 score.student_id 與 student.id 相匹配的所有 score 值的最大值。
- update 語句將 student.score 字段更新為該最大值。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END