MySQL 错误 : column cannot be null in update query

标签 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);

问题是我想检查更新,以便该值不会低于零。我想在 case when 这样的语句中加入一个额外的条件

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

但它会抛出错误“保留的列不能为空”。我该如何解决这个问题?

最佳答案

因为 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);

关于MySQL 错误 : column cannot be null in update query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671963/

相关文章:

mysql - 在 MySQL 中使用 CASE 转换 NULL 时遇到问题

python - Python 3.+ 中另一个交替大小写的字符串

php - 我的 mysql 结果集重复了?为什么

mysql - 为什么我在更新 sql 时遇到这个 MySql 错误

mysql - Full Outer Join 与 Union 重复?

mysql - magento1.4v 和 1.5v 数据库的区别

mysql - 为每一行使用多个 'where' 子句更新多行

使用 Join 和 CASE..ELSE 语法更新 MySQL 存储过程

Mysql:更新命令没有改变

mysql - 如何在 mysql 中自动创建学号?