0
は、私は、次のデータベース・スキーマを持っていると仮定します。 schema更新複数の列
生徒が同じテーマで2つの以上の等級を持つことができます。
テーブルstudentのカラム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);
しかし、それは私が望んでいないものを一度更新するだけです。
1つの更新ステートメントで同じことを達成する方法はありますか?