MySQL casting of -1 returns 18446744073709551615

后端 未结 1 1738
借酒劲吻你
借酒劲吻你 2021-01-18 06:24

I can\'t seem to find an explanation for this and I\'m pretty sure that it has previously worked as expected.

SELECT CAST(-1 AS UNSIGNED INTEGER);

相关标签:
1条回答
  • 2021-01-18 06:51

    From the docs:

    MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using numeric operators (such as + or -) and one of the operands is an unsigned integer, the result is unsigned by default (see Section 11.6.1, “Arithmetic Operators”). You can override this by using the SIGNED or UNSIGNED cast operator to cast a value to a signed or unsigned 64-bit integer, respectively.

    mysql> SELECT CAST(1-2 AS UNSIGNED)
           -> 18446744073709551615
    mysql> SELECT CAST(CAST(1-2 AS UNSIGNED) AS SIGNED);
           -> -1
    

    Basically, with you cast you tell MySQL how to treat 0xFFFFFFFFFFFFFFFF. It's -1 when signed, 18446744073709551615 when unsigned.

    0 讨论(0)
提交回复
热议问题