MySQL Update Left Join 更新最大值:如何使用子查詢從多條數(shù)據(jù)中獲取最大值并更新特定字段?

MySQL Update Left Join 更新最大值:如何使用子查詢從多條數(shù)據(jù)中獲取最大值并更新特定字段?

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)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊9 分享