如何更新满足不同条件的多行

时间:2013-08-21 18:08:12

标签: mysql

我想更新满足不同条件的多行

Result
Student_No  Subject_No Marks

ST101         SU03     69
ST102         SU01     3
ST101         SU04     45
ST101         SU05     87
ST103         SU01     44
ST103         SU03     50
ST103         SU01     56
ST108         SU01     78
ST105         SU05     98

我希望通过添加增量来增加所有主题的分数,如下所示: 让增量 0-24 8 30-36 7 44-54 5

感谢。 单

2 个答案:

答案 0 :(得分:1)

UPDATE MARKSTABLE
   SET MARKS=MARKS+IF(MARKS BETWEEN 0 AND 24, 8, IF(MARKS BETWEEN 30 AND 36, 7, IF(MARKS BETWEEN 44 AND 54, 5, 0)))

答案 1 :(得分:0)

最自然的方法是使用案例陈述:

update Result
    set Marks = Marks + (case when Marks between 0 and 24 then 8
                              when Marks between 30 and 36 then 7
                              when Marks between 44 and 54 then 5
                              else 0
                         end);

您也可以使用join执行此操作,这样可以更轻松地添加新范围:

update Results join
       (select 0 as lb, 24 as ub, 8 as inc union all
        select 30, 36, 7
        select 44, 54, 5
       ) ranges
       on Results.Marks between ranges.lb and ranges.ub
    Results.Marks = Results.Marks + ranges.inc;