更新查询后mysql中的值重置为0

时间:2014-09-18 19:36:09

标签: mysql

这就是我的表格

_____________________________________________________________
|  id  |  val1  |  val2  |  val3  |  val4  |  val5  |  val6  |
|______|________|________|________|________|________|________|
|   1  |  1300  |  1300  |     0  |  2000  |  1300  |     0  |
|______|________|________|________|________|________|________|
|  10  |     0  |     0  |     0  |  2000  |     0  |     0  |
|______|________|________|________|________|________|________|

现在我更新

UPDATE points set val5 = CASE WHEN id = 10 THEN val5 + 500 WHEN id = 1 THEN val5 + 500 END WHERE id IN ('10','1')

这就是我的表格

_____________________________________________________________
|  id  |  val1  |  val2  |  val3  |  val4  |  val5  |  val6  |
|______|________|________|________|________|________|________|
|   1  |  1800  |  1800  |     0  |  2000  |  1800  |     0  |
|______|________|________|________|________|________|________|
|  10  |   500  |   500  |     0  |  2000  |   500  |     0  |
|______|________|________|________|________|________|________|
| 157  |     0  |     0  |     0  |   800  |     0  |     0  |
|______|________|________|________|________|________|________|

现在我再次更新(这是它被打破的地方)

UPDATE points set val5 = CASE WHEN id = 1 THEN val5 + 500 END, val6 = CASE WHEN id = 10 THEN val6 + 500 END WHERE id IN ('10','1')

我的表格看起来像这样

_____________________________________________________________
|  id  |  val1  |  val2  |  val3  |  val4  |  val5  |  val6  |
|______|________|________|________|________|________|________|
|   1  |  2300  |  2300  |     0  |  2000  |  2300  |     0  |
|______|________|________|________|________|________|________|
|  10  |  1000  |     0  |   500  |  2000  |     0  |   500  |
|______|________|________|________|________|________|________|
| 157  |     0  |     0  |     0  |   800  |     0  |     0  |
|______|________|________|________|________|________|________|
| 158  |     0  |     0  |     0  |   800  |     0  |     0  |
|______|________|________|________|________|________|________|

你是否注意到val2和val5如何回归零,即使我没有告诉它?我错过了什么?

2 个答案:

答案 0 :(得分:2)

如果表达式与when中的任何case子句不匹配,则返回null,这不是您想要的行为。相反,您应该在else子句中返回列本身:

UPDATE points 
SET    val5 = CASE WHEN id = 1 THEN val5 + 500 ELSE val5 END, -- Notice the else
       val6 = CASE WHEN id = 10 THEN val6 + 500 ELSE val6 END -- Here too
WHERE  id IN (10, 1)

答案 1 :(得分:1)

对于第一个查询,您甚至不需要CASE语句。以下应该有效:

UPDATE points 
SET val5 = val5 + 500
WHERE id IN (10, 1)

对于第二个查询,您必须拥有ELSE语句:

UPDATE points 
SET val5 = CASE WHEN id = 1 THEN val5 + 500 ELSE val5 END, 
    val6 = CASE WHEN id = 10 THEN val6 + 500 ELSE val6 END 
WHERE id IN (10, 1)

我注意到了另外一件事。您在CASE语句中使用id = 1id = 10。但是,然后在WHERE语句中使用id IN ('10','1')。那么,id是一个字符串或数字。在上面的示例中,我将其更改为数字。