MySQL BIGINT UNSIGNED value is out of range... 的问题和解决

时间:2022-03-15 16:32:33
MySQL处理两个整数(INT)相减的时候,如果其中有一个是UNSIGNED INT类型的,那么结果就被当做是UNSIGNED的。
如果相减的结果是负数:
  • 在MySQL 5.5.5之前,结果变成了最大的整数(18446744073709551615)
  • 从MySQL 5.5.5开始,这种情况会返回一个错误:BIGINT UNSIGNED value is out of range... 
比如:
如果结果为负数: [SQL] SELECT (CAST(0 AS UNSIGNED)-1); [Err] 1690 - BIGINT UNSIGNED value is out of range in '(cast(0 as unsigned) - 1)'
[SQL] SELECT (1-CAST(2 AS UNSIGNED)); [Err] 1690 - BIGINT UNSIGNED value is out of range in '(1 - cast(2 as unsigned))'
如果结果为正数: [SQL] SELECT (1-CAST(0 AS UNSIGNED)); 1
解决方法: 1、如果确实可以接受负数的结果,那么把其中的UNSIGNED字段强转为SIGNED类型: [SQL] SELECT (1-CAST(2 ASSIGNED)); -1
如果计算结果是要插入到另外一个UNSIGNED INT字段中的话,那么就不要强转了,直接捕捉并报告异常。
 参考:http://dev.mysql.com/doc/refman/5.6/en/out-of-range-and-overflow.html
(原创文章,转载请注明转自Clement-Xu的博客