我有一个运行良好的 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);
问题是我想检查更新,以便该值不会低于零。我想在 case when 这样的语句中加入一个额外的条件
WHEN location_id = 13 and variant_id = 20 and reserved > 0 then 3
但它会抛出错误“保留的列不能为空”。我该如何解决这个问题?
最佳答案
因为 CASE
表达式中的条件与 WHERE
子句中的条件不匹配,所以您的 需要一个
表达式,以便当 ELSE
子句>CASEWHEN
条件都不为真时,您不会返回 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);
关于MySQL 错误 : column cannot be null in update query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671963/