无符号类型转换问题

【 TiDB 使用环境】生产环境 /测试/ Poc
【 TiDB 版本】
【复现路径】做过哪些操作出现的问题
【遇到的问题:问题现象及影响】
【资源配置】进入到 TiDB Dashboard -集群信息 (Cluster Info) -主机(Hosts) 截图此页面
【附件:截图/日志/监控】

mysql> create table a1(id int not null auto_increment primary key,name varchar(20), total bigint unsigned);
Query OK, 0 rows affected (0.12 sec)

mysql> insert into a1 values(null,'a',15);
Query OK, 1 row affected (0.06 sec)

mysql> select * from a1;
+----+------+-------+
| id | name | total |
+----+------+-------+
|  1 | a    |    15 |
+----+------+-------+
1 row in set (0.00 sec)

mysql> select 14-total from a1;
ERROR 1690 (22003): BIGINT UNSIGNED value is out of range in '(14 - `hhm`.`a1`.`total`)

这种的低层是如何类型转换的?

BIGINT UNSIGNED只支持正数啊
你这14-15 结果是-1 怎么存储在BIGINT UNSIGNED类型下呢?

这个类型转换还有个问题是需要和mysql保持一致。

看上去有人也在mysql提过这个问题。
结论也是这不是个bug。

如果不想看到这个错误就强转一下。

https://bugs.mysql.com/bug.php?id=83902

[4 Jan 2020 10:17] Roy Lyseng
Posted by developer:

This is not a bug.
The CRC32 function produces an UNSIGNED value, and the UNSIGNED property is propagated to the addition operator.
Workaround is to convert the CRC32 result to a signed integer:

select ((floor(-(401))) * CAST(CRC32(0) AS SIGNED));

也可以强制修改select 结果的数据类型 SELECT 14 - CAST(total AS SIGNED) FROM a1;

select的结果类型是如何定义的,按表结构字段的定义?

MySQL官方文档找到了:
Subtraction between integer values, where one is of type UNSIGNED , produces an unsigned result by default. If the result would otherwise have been negative, an error results:

mysql> alter table a1 add sum bigint;
Query OK, 0 rows affected (0.29 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> select * from a1;
+----+------+-------+------+
| id | name | total | sum  |
+----+------+-------+------+
|  1 | a    |    15 | NULL |
+----+------+-------+------+
1 row in set (0.01 sec)

mysql> update a1 set sum=15;
Query OK, 1 row affected (0.03 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select 14-sum from a1;
+--------+
| 14-sum |
+--------+
|     -1 |
+--------+
1 row in set (0.01 sec)

SELECT语句的结果集本身并没有存储在数据库中的字段类型,它只是一个临时的结果集,但是,每个表达式或计算的结果都会有一个隐含的数据类型,这个数据类型是由 SQL 引擎根据输入数据类型和操作确定的。

此话题已在最后回复的 60 天后被自动关闭。不再允许新回复。