代码之家  ›  专栏  ›  技术社区  ›  Eugen Konkov

Postgres:整数超出范围。为什么会发生这种错误?

  •  1
  • Eugen Konkov  · 技术社区  · 6 年前

    429496729600 ,但其中一个因错误而失败:

    db=> update order_detail set amount = 400*1024*1024*1024 where id = 11;
    ERROR:  integer out of range
    db=> update order_detail set amount = 429496729600 where id = 11;
    UPDATE 1
    

    为什么第一次查询会出错?

    升级版
    amount bigint

    400*1024*1024*1024 == 429496729600  
    
    2 回复  |  直到 6 年前
        1
  •  8
  •   JGH    6 年前

    要强制乘法输出bigint而不是int,可以将1强制转换为bigint并进行乘法

    select cast(1 as bigint)*400*1024*1024*1024;
       ?column?
    --------------
     429496729600
    
        2
  •  1
  •   D-Shih    6 年前

    int 最大值2 31

    INT -2147483648至+2147483647

    amount 列到 BIGINT

    比基特 -9223372036854775808至9223372036854775807

    ALTER TABLE order_detail ALTER COLUMN amount TYPE BIGINT;
    

    Data Types


    pg_typeof 去看看。

    查询#1

    429496729600 比基特

    SELECT pg_typeof(429496729600 );
    
    | pg_typeof |
    | --------- |
    | bigint    |
    

    查询#2

    当你做乘法的时候 内景 .

    SELECT pg_typeof( 1*15*1  );
    
    | pg_typeof |
    | --------- |
    | integer   |
    

    View on DB Fiddle

    查询

    400*1024*1024*1024:: BIGINT 转换为 bigint

    SELECT 400*1024*1024*1024 :: BIGINT;
    
    | ?column?     |
    | ------------ |
    | 429496729600 |
    

    View on DB Fiddle