MYSQL错误:更新查询中的栏位不能为null

时间:2019-04-14 04:26:06

标签: mysql sql-update case

我有一个运行良好的SQL更新查询。

Update inventory set reserved = reserved - 
CASE 
    WHEN location_id = 23 and variant_id = 40 then 2
    WHEN location_id = 13 and variant_id = 20 then 3
end 
where (location_id = 23 and variant_id = 40) or 
      (location_id = 13 and variant_id = 20);

问题是我要检查更新,以便该值不会低于零。我当时想在这种情况下加一个额外条件

WHEN location_id = 13 and variant_id = 20 and reserved > 0 then 3

但是会引发错误“保留的列不能为空”。我该怎么解决?

1 个答案:

答案 0 :(得分:2)

由于CASE表达式中的条件与WHERE子句中的条件不匹配,因此您需要在ELSE表达式中使用CASE子句,以便当WHEN条件为真,则您没有返回NULL值,否则将导致

reserved - (CASE ...) 

成为NULL,给您看到的错误。试试这个:

Update inventory set reserved = reserved - 
CASE 
    WHEN location_id = 23 and variant_id = 40 then 2
    WHEN location_id = 13 and variant_id = 20 and reserved > 0 then 3
    ELSE 0
end 
where (location_id = 23 and variant_id = 40) or 
      (location_id = 13 and variant_id = 20);

或者,为防止该值小于0,您可能要考虑使用LEAST来防止减去一个大于当前reserved值的值,例如

Update inventory set reserved = reserved - 
CASE 
    WHEN location_id = 23 and variant_id = 40 then LEAST(2, reserved)
    WHEN location_id = 13 and variant_id = 20 then LEAST(3, reserved)
end 
where (location_id = 23 and variant_id = 40) or 
      (location_id = 13 and variant_id = 20);