2017-11-09 15 views
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つの更新ステートメントで同じことを達成する方法はありますか?

答えて

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