mysql update 語句使用 left join 更新多條數據中的最大字段值
在關系型數據庫中,有時候需要更新表中的某一列為其他表中相關行的最大值。對于 mysql 而言,可以使用 left join 來實現這樣的更新操作。
考慮我們有以下兩個表:
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 |
我們的目標是將 student 表中每個學生的 score 字段更新為其在 score 表中對應的最大值。
為了使用 left join 來實現此更新,我們需要使用以下 sql 語句:
update student set score=(select max(score) from score where score.student_id=student.id)
在這個語句中:
- update student 部分指定要更新的表是 student 表。
- set score=(select max(score) from score where score.student_id=student.id) 部分定義了要更新的字段值。
- 子查詢 (select max(score) from score where score.student_id=student.id) 從 score 表中選擇每個學生的最大分值,其中 where 子句確保只選擇與學生匹配的分值。
執行此語句后,student 表中每個學生的 score 字段將更新為其在 score 表中對應的最大值:
id | name | score |
---|---|---|
1 | 小明 | 80 |
2 | 小紅 | 98 |
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END