假设我有以下数据库架构: schema
学生可以在同一科目中获得2个以上的成绩。
我想更新表学生的列highest_math_grade,highest_physic_grade,highest_chemistry_grade。我就是这样做的:
UPDATE student JOIN (
SELECT student.id, MAX(grade) AS grade
FROM student join grade
ON student.id = grade.student_id
WHERE subject = 'math'
GROUP BY student.id
) AS subquery
ON student.id = subquery.id
SET highest_math_grade = subquery.grade;
UPDATE student JOIN (
SELECT student.id, MAX(grade) AS grade
FROM student join grade
ON student.id = grade.student_id
WHERE subject = 'physic'
GROUP BY student.id
) AS subquery
ON student.id = subquery.id
SET highest_physic_grade = subquery.grade;
UPDATE student JOIN (
SELECT student.id, MAX(grade) AS grade
FROM student join grade
ON student.id = grade.student_id
WHERE subject = 'chemistry'
GROUP BY student.id
) AS subquery
ON student.id = subquery.id
SET highest_chemistry_grade = subquery.grade;
我不得不使用3个更新语句。我试过了:
UPDATE student
JOIN (SELECT *
FROM grade
ORDER BY grade) AS grade
ON student.id = grade.student_id
SET highest_math_grade = (CASE WHEN grade.subject = 'math'
THEN grade.grade
ELSE highest_math_grade END),
highest_chemistry_grade = (CASE WHEN grade.subject = 'chemistry'
THEN grade.grade
ELSE highest_chemistry_grade END),
highest_physic_grade = (CASE WHEN grade.subject = 'physic'
THEN grade.grade
ELSE highest_physic_grade END);
然而,它只会更新每个学生一次,这不是我想要的。
有没有办法只用一个更新语句来实现同样的目的?
答案 0 :(得分:0)
试试这个答案,希望这会对你有所帮助:
UPDATE S SET S.highest_math_grade=Math_Grade
,S.highest_chemistry_grade =chemistry_Grade
,S.highest_physic_grade=physic_Grade
FROM STUDENT S,(
SELECT S.ID
,MAX(G1.grade)Math_Grade
,MAX(G2.grade)chemistry_Grade
,MAX(G3.grade)physic_Grade
FROM STUDENT S
LEFT JOIN Grade G1 ON S.id=G1.student_id AND G1.subject = 'math'
LEFT JOIN Grade G2 ON S.id=G2.student_id AND G2.subject = 'chemistry'
LEFT JOIN Grade G3 ON S.id=G3.student_id AND G3.subject = 'physic'
GROUP BY S.ID
)D
WHERE S.ID=D.ID