如果在访问另一个表时必须满足条件,如何更新具有多个案例的表?

时间:2017-10-26 15:05:20

标签: mysql

问题在于:

通过使用case子句,编写一个表示以下更新的SQL语句: “在每名学生获得满意的学分总数中加上+4,即等级至少为'B +',即计算机科学课程标识'CS-347';如果学生通过了“B”或“C +”成绩考试,则加上+3;如果学生没有通过考试(即成绩为'F'),最后加-3。

我的猜测是:

UPDATE student as S
SET S.tot_cred = CASE
WHEN (SELECT grade
     FROM takes as T
     WHERE T.ID = S.ID) = ('B+', 'A-', 'A', 'A+') 
     OR (SELECT course_id
     FROM takes as T
     WHERE T.ID = S.ID) = 'CS-347'
     THEN tot_cred + 4
WHEN (SELECT grade
     FROM takes as T
     WHERE T.ID = S.ID) = ('C+', 'B')
     THEN tot_cred + 3
WHEN (SELECT grade
     FROM takes as T
     WHERE T.ID = S.ID) = 'F'
THEN tot_cred - 3
END

但是,我收到错误消息:#1241 - 操作数应包含1列。

1 个答案:

答案 0 :(得分:1)

CASE表达式返回单个值。因此,您需要将逻辑放在CASE上以查看您需要的值。

所以这样:

CASE WHEN grade IN ('B+', 'A-', 'A', 'A+') THEN +4
     WHEN grade IN ('C+', 'B') THEN +3
     ELSE -3
END

您的最终查询应该是JOIN,您可以获得所有TAKES

的总积分
UPDATE student as S
JOIN (SELECT T.ID, SUM ( CASE WHEN grade IN ('B+', 'A-', 'A', 'A+') THEN +4
                              WHEN grade IN ('C+', 'B') THEN +3
                              ELSE -3
                         END ) as total_credits
      FROM Takes as T
      GROUP BY T.ID -- all the grades for the student
     ) as T
   ON S.ID = T.ID
SET S.tot_cred =  S.tot_cred + T.total_credits