如何使用 MySQL update 語句與 left join 獲取多條數(shù)據(jù)中的最大值?

如何使用 MySQL update 語句與 left join 獲取多條數(shù)據(jù)中的最大值?

mysql 數(shù)據(jù)庫(kù)中 update 語句 left join 獲取多條數(shù)據(jù)中最大值

mysql 中的 update 語句可以用于更新表中的數(shù)據(jù)。如果需要更新某一字段的值為其他表中多條數(shù)據(jù)中某字段的最大值,可以使用 left join 來實(shí)現(xiàn)。

問題背景

我們有一張 student 表,其中包含學(xué)生姓名 name 和分?jǐn)?shù) score 字段。還有一張 score 表,其中包含學(xué)生的分?jǐn)?shù)記錄,每個(gè)學(xué)生可能有多次分?jǐn)?shù)記錄。

更新語句

要將 student 表中 score 字段更新為 score 表中每個(gè)學(xué)生的最高分,可以使用以下 update 語句:

update student set score = (select max(score) from score where score.student_id = student.id)

left join 用法

left join 語法將 student 表與 score 表連接,并返回 student 表中的所有行,即使這些行在 score 表中沒有匹配項(xiàng)。如果 student 表中的某一行在 score 表中有多條匹配項(xiàng),則 left join 將返回其中包含最大分?jǐn)?shù)的那條記錄。

查詢示例

更新后的 student 表如下所示:

id name score
1 小明 80
2 小紅 98

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊13 分享