在SQL中如何获取整数的最大值?

时间:2010-04-20 22:13:12

标签: sql mysql

我试图从MySQL数据库中找出整数(有符号或无符号)的最大值。有没有办法从数据库本身撤回这些信息?

是否有我可以使用的内置常量或函数(标准SQL或MySQL特定)。

http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html它会列出值 - 但数据库是否有办法告诉我。

以下给出了MAX_BIGINT - 我想要的是MAX_INT。

SELECT CAST( 99999999999999999999999 AS SIGNED ) as max_int;
# max_int | 9223372036854775807

提前致谢,

2 个答案:

答案 0 :(得分:67)

在Mysql中有一个便宜的技巧:

mysql> select ~0;
+----------------------+
| ~0                   |
+----------------------+
| 18446744073709551615 |
+----------------------+

波浪号是按位否定。结果值很大。请参阅:http://dev.mysql.com/doc/refman/5.1/en/bit-functions.html#operator_bitwise-invert

对于其他整数风格,您可以使用正确的bitshift运算符>>,如下所示:

SELECT ~0 as max_bigint_unsigned
,      ~0 >> 32 as max_int_unsigned
,      ~0 >> 40 as max_mediumint_unsigned
,      ~0 >> 48 as max_smallint_unsigned
,      ~0 >> 56 as max_tinyint_unsigned
,      ~0 >> 1  as max_bigint_signed
,      ~0 >> 33 as max_int_signed
,      ~0 >> 41 as max_mediumint_signed
,      ~0 >> 49 as max_smallint_signed
,      ~0 >> 57 as max_tinyint_signed
\G

*************************** 1. row ***************************
   max_bigint_unsigned: 18446744073709551615
      max_int_unsigned: 4294967295
max_mediumint_unsigned: 16777215
 max_smallint_unsigned: 65535
  max_tinyint_unsigned: 255
     max_bigint_signed: 9223372036854775807
        max_int_signed: 2147483647
  max_mediumint_signed: 8388607
   max_smallint_signed: 32767
    max_tinyint_signed: 127
1 row in set (0.00 sec)

答案 1 :(得分:-2)

似乎没有任何内置常量来提供这些值。由于它们很可能不会发生变化,因此您应该安全地对它们进行硬编码或将其值设置为查找表或变量。