使用条件MYSQL更新具有其他字段总和的字段

时间:2015-06-30 12:33:25

标签: mysql

我的表格结构如下

counter1|counter1_status|counter2|counter2_status|counter3|counter3_status|valid_counter
-----------------------------------------------------------------------------------------
 5                 0             6            1               3               1                XXXX

我想要一个更新查询来将valid_counter更新为6 + 3 = 9 由于counter1_status = 0,因此不应添加counter1

尝试了以下查询,但它给出了错误。

UPDATE counter_table 
SET valid_contact = 
SUM((CASE WHEN counter1_status=1 THEN counter1 ELSE 0 END) 
+ (CASE WHEN counter2_status=1 THEN counter2 ELSE 0 END) 
+ (CASE WHEN counter3_status=1 THEN counter3 ELSE 0 END)) 

我可以通过使用SELECT查询获得总和而没有任何错误,但更新查询失败。

3 个答案:

答案 0 :(得分:0)

如果你想在valid_contace字段中有条件地存储(counter1,counter2,counter3)的总和,你可以使用:

UPDATE counter_table 
SET valid_contact = 
(CASE WHEN counter1_status=1 THEN counter1 ELSE 0 END) 
+ (CASE WHEN counter2_status=1 THEN counter2 ELSE 0 END) 
+ (CASE WHEN counter3_status=1 THEN counter3 ELSE 0 END)
where id=5

答案 1 :(得分:0)

UPDATE counter_table AS c1 JOIN 
(SELECT id, SUM((CASE WHEN counter1_status=1   THEN counter1 ELSE 0 END) 
    + (CASE WHEN counter2_status=1 THEN counter2 ELSE 0 END) 
    + (CASE WHEN counter3_status=1 THEN counter3 ELSE 0 END)) AS m 
FROM counter_table) AS c2
    USING (id)
    SET c1.`valid_counter` = c2.m;

<强> Sample fiddle

答案 2 :(得分:0)

最后得到了错误的解决方案:

应该从查询中删除SUM。

它应该是SUM(a,b,c)

或a + b + c。

更新counter_table SET valid_contact = ((例如,当counter1_status = 1那么counter1 ELSE 0 END) +(例如,当counter2_status = 1那么counter2 ELSE 0 END) +(例如,当counter3_status = 1那么counter3 ELSE 0 END))