数值超出范围:1690 BIGINT UNSIGNED 值超出范围

Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in

我有一个问题:

update `shops` set
    `points` = `points` - 2,
    `updated_at` = '2019-04-17 23:07:11'
where `id` = 4;

列点有一个列类型:BIGINT(20)。

现在在记录中我的值为 62。当我 运行 上面的查询时我得到这个错误:

SQLSTATE[22003]: Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in '(`database`.`shops`.`points` - 2)'

不一样。

这会起作用:

 set `points` = `points` - cast(2 AS SIGNED)

`updated_at` = '2019-04-17 23:07:11'

您不能在无符号整数中存储负值。更安全的解决方案是在执行减法之前检查操作数:

SET points = CASE WHEN points >= 2 THEN points - 2 ELSE 0 END

或者简单地说:

SET points = points - LEAST(points, 2)