我们知道,如果在数值表达式的评估期间发生溢出,MySQL将产生错误。例如,最大的有符号BIGNT是9223372036854775807,因此以下表达式将产生错误-
mysql> Select 9223372036854775807 + 1; ERROR 1690 (22003): BIGINT value is out of range in '(9223372036854775807+1)'
MySQL可以通过以下方式处理此类溢出:
MySQL通过将值转换为unsigned来实现这种操作,如下所示:
mysql> Select CAST(9223372036854775807 AS UNSIGNED) +1; +------------------------------------------+ | CAST(9223372036854775807 AS UNSIGNED) +1 | +------------------------------------------+ | 9223372036854775808 | +------------------------------------------+ 1 row in set (0.07 sec)
MySQL可以使用精确值算法来处理前面的表达式。这是因为发生溢出取决于操作数的范围。例如,可以通过使用DECIMAL值进行以下计算,如下所示:
mysql> Select 9223372036854775807.0 + 1; +---------------------------+ | 9223372036854775807.0 + 1 | +---------------------------+ | 9223372036854775808.0 | +---------------------------+ 1 row in set (0.01 sec)