更新查询时的MYSQL案例

时间:2012-09-29 10:19:05

标签: mysql sql

这是我的桌子。

我需要做的是创建一个CASE WHEN UPDATE Query来更新

  • CurrentCredit +1 if 1-15

  • CurrentCredit +2 if 16-30

  • CurrentCredit x.10并在> = 31

  • 时向上舍入

1 个答案:

答案 0 :(得分:6)

看一下示例

SQL Fiddle DEMO

Somethign like

UPDATE MyTable
SET CurrentCredit = 
CASE 
  WHEN CurrentCredit BETWEEN 1 AND 15
    THEN CurrentCredit + 1
  WHEN CurrentCredit BETWEEN 16 AND 30
    THEN CurrentCredit +2
  WHEN CurrentCredit >= 31
    THEN CurrentCredit * 10
  ELSE CurrentCredit
END

另外,请记住,如果CurrentCredit是FLOAT而不是INT,您可能想要尝试类似

的内容
UPDATE MyTable
SET CurrentCredit = 
CASE 
  WHEN CurrentCredit >= 1 AND CurrentCredit < 16
    THEN CurrentCredit + 1
  WHEN CurrentCredit >= 16 AND CurrentCredit < 31
    THEN CurrentCredit +2
  WHEN CurrentCredit >= 31
    THEN CurrentCredit * 10
  ELSE CurrentCredit
END;

修改

对于更正的请求(&gt; = 31 CurrentCredit + CEILING(CurrentCredit * 0.1)),请查看使用CEILING

UPDATE MyTable
SET CurrentCredit = 
CASE 
  WHEN CurrentCredit BETWEEN 1 AND 15
    THEN CurrentCredit + 1
  WHEN CurrentCredit BETWEEN 16 AND 30
    THEN CurrentCredit +2
  WHEN CurrentCredit >= 31
    THEN CurrentCredit + CEILING(CurrentCredit * 0.1)
  ELSE CurrentCredit
END;

SQL Fiddle DEMO