为什么 CAST(1 AS SIGNED INTEGER) 在 MySQL 上返回 BIGINT?

Kev*_*Kev 9 mysql mysql-5.5

如果我这样做,CAST(1 AS SIGNED INTEGER)我总是最终得到BIGINT退货,例如:

$ mysql -u root -p --column-type-info
Enter password:

--- Copyright and help message snipped for brevity ---

mysql> select cast(1 as signed integer);
Field   1:  `cast(1 as signed integer)`
Catalog:    `def`
Database:   ``
Table:      ``
Org_table:  ``
Type:       LONGLONG            <== LONGLONG i.e. 64 bit integer
Collation:  binary (63)
Length:     1
Max_length: 1
Decimals:   0
Flags:      NOT_NULL BINARY NUM


+---------------------------+
| cast(1 as signed integer) |
+---------------------------+
|                         1 |
+---------------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

我原以为该转换的返回类型是LONG(32 位整数)。

如果我从一个表中选择一列,INT我看到它确实只是一个LONG

mysql> describe contact;

+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| contact_id | int(11) | NO   | PRI | NULL    | auto_increment |

      == remainder of table snipped ==

mysql> select contact_id from contact where contact_id = 20;
Field   1:  `contact_id`
Catalog:    `def`
Database:   `centreon`
Table:      `contact`
Org_table:  `contact`
Type:       LONG                     <== LONG i.e. 32 bit integer
Collation:  binary (63)
Length:     11
Max_length: 2
Decimals:   0
Flags:      NOT_NULL PRI_KEY AUTO_INCREMENT NUM PART_KEY


+------------+
| contact_id |
+------------+
|         20 |
+------------+
1 row in set (0.00 sec)

mysql>
Run Code Online (Sandbox Code Playgroud)

如果我将同一列转换为有符号整数,我将再次返回一个 64 位整数:

mysql> select CAST(contact_id as signed integer) from contact where contact_id = 20;
Field   1:  `CAST(contact_id as signed integer)`
Catalog:    `def`
Database:   ``
Table:      ``
Org_table:  ``
Type:       LONGLONG
Collation:  binary (63)
Length:     11
Max_length: 2
Decimals:   0
Flags:      NOT_NULL BINARY NUM


+------------------------------------+
| CAST(contact_id as signed integer) |
+------------------------------------+
|                                 20 |
+------------------------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

这里有一个类似的报告问题:

http://bugs.mysql.com/bug.php?id=64084

但遗憾的是,OP 没有得到直接的答案。

这是CAST()功能中的错误还是设计使然?

小智 -1

MySQL 中 int 存储为 32 位。

MySQL 支持有符号和无符号 64 位值的算术。对于数字运算符(例如 + 或 -),其中操作数之一是无符号整数,则默认情况下结果是无符号的。要覆盖此设置,请使用 SIGNED 或 UNSIGNED 强制转换运算符将值分别强制转换为有符号或无符号 64 位整数。

这就是为什么对于 int 它显示 long int :32 位

对于signed int,它显示long long int OR BIG int:64 int