我有一个运行良好的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
但是会引发错误“保留的列不能为空”。我该怎么解决?
答案 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);