导读

作者徐晨亮,MySQL DBA,知数堂学员。热衷于数据库优化,自动化运维及数据库周边工具开发,对MySQL源码有一定的兴趣

本文建议横屏观看,效果更佳


一、问题描述

root@mysqldb 22:12:  [xucl]> show create table t1\G*************************** 1. row ***************************       Table: t1Create Table: CREATE TABLE `t1` (  `id` varchar(255) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf81 row in set (0.00 sec)

root@mysqldb 22:19:  [xucl]> select * from t1;+--------------------+| id                 |+--------------------+| 204027026112927605 || 204027026112927603 || 2040270261129276   || 2040270261129275   || 100                || 101                |+--------------------+6 rows in set (0.00 sec)

奇怪的现象:

root@mysqldb 22:19:  [xucl]> select * from t1 where id=204027026112927603;+--------------------+| id                 |+--------------------+| 204027026112927605 || 204027026112927603 |+--------------------+2 rows in set (0.00 sec)

什么鬼,明明查的是204027026112927603,为什么204027026112927605也出来了

二、源码解释

堆栈调用关系如下所示:

其中JOIN::exec()是执行的入口,Arg_comparator::compare_real()是进行等值判断的函数,其定义如下

int Arg_comparator::compare_real(){  /*    Fix yet another manifestation of Bug#2338. 'Volatile' will instruct    gcc to flush double values out of 80-bit Intel FPU registers before    performing the comparison.  */  volatile double val1, val2;  val1= (*a)->val_real();  if (!(*a)->null_value)  {    val2= (*b)->val_real();    if (!(*b)->null_value)    {      if (set_null)        owner->null_value= 0;      if (val1 < val2)  return -1;      if (val1 == val2) return 0;      return 1;    }  }  if (set_null)    owner->null_value= 1;  return -1;}

比较步骤如下图所示,逐行读取t1表的id列放入val1,而常量204027026112927603存在于cache中,类型为double类型(2.0402702611292762E+17),所以到这里传值给val2后val2=2.0402702611292762E+17。

当扫描到第一行时,204027026112927605转成doule的值为2.0402702611292762e17,等式成立,判定为符合条件的行,继续往下扫描,同理204027026112927603也同样符合

如何检测string类型的数字转成doule类型是否溢出呢?这里经过测试,当数字超过16位以后,转成double类型就已经不准确了,例如20402702611292711会表示成20402702611292712(如图中val1)

MySQL string转成double的定义函数如下:

{  char buf[DTOA_BUFF_SIZE];  double res;  DBUG_ASSERT(end != NULL && ((str != NULL && *end != NULL) ||                              (str == NULL && *end == NULL)) &&              error != NULL);

  res= my_strtod_int(str, end, error, buf, sizeof(buf));  return (*error == 0) ? res : (res < 0 ? -DBL_MAX : DBL_MAX);}

真正转换函数my_strtod_int位置在dtoa.c(太复杂了,简单贴个注释吧)

/*  strtod for IEEE--arithmetic machines.

  This strtod returns a nearest machine number to the input decimal  string (or sets errno to EOVERFLOW). Ties are broken by the IEEE round-even  rule.

  Inspired loosely by William D. Clinger's paper "How to Read Floating  Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].

  Modifications:

   1. We only require IEEE (not IEEE double-extended).   2. We get by with floating-point arithmetic in a case that     Clinger missed -- when we're computing d * 10^n     for a small integer d and the integer n is not too     much larger than 22 (the maximum integer k for which     we can represent 10^k exactly), we may be able to     compute (d*10^k) * 10^(e-k) with just one roundoff.   3. Rather than a bit-at-a-time adjustment of the binary     result in the hard case, we use floating-point     arithmetic to determine the adjustment to within     one bit; only in really hard cases do we need to     compute a second residual.   4. Because of 3., we don't need a large table of powers of 10     for ten-to-e (just some small tables, e.g. of 10^k     for 0 <= k <= 22).*/

既然是这样,我们测试下没有溢出的案例

root@mysqldb 23:30:  [xucl]> select * from t1 where id=2040270261129276;+------------------+| id               |+------------------+| 2040270261129276 |+------------------+1 row in set (0.00 sec)

root@mysqldb 23:30:  [xucl]> select * from t1 where id=101;+------+| id   |+------+| 101  |+------+1 row in set (0.00 sec)

结果符合预期,而在本例中,正确的写法应当是

root@mysqldb 22:19:  [xucl]> select * from t1 where id='204027026112927603';+--------------------+| id                 |+--------------------+| 204027026112927603 |+--------------------+1 row in set (0.01 sec)

三、结论

  1. 避免发生隐式类型转换,隐式转换的类型主要有字段类型不一致、in参数包含多个类型、字符集类型或校对规则不一致等

  2. 隐式类型转换可能导致无法使用索引、查询结果不准确等,因此在使用时必须仔细甄别

  3. 数字类型的建议在字段定义时就定义为int或者bigint,表关联时关联字段必须保持类型、字符集、校对规则都一致

  4. 最后贴一下官网对于隐式类型转换的说明吧

1、If one or both arguments are NULL, the result of the comparison is NULL, except for the NULL-safe<=> equality comparison operator. For NULL <=> NULL, the result is true. No conversion is needed.2、If both arguments in a comparison operation are strings, they are compared as strings.3、If both arguments are integers, they are compared as integers.4、Hexadecimal values are treated as binary strings if not compared to a number.5、If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is aconstant, the constant is converted to a timestamp before the comparison is performed. This isdone to be more ODBC-friendly. This is not done for the arguments to IN(). To be safe, alwaysuse complete datetime, date, or time strings when doing comparisons. For example, to achieve bestresults when using BETWEEN with date or time values, use CAST() to explicitly convert the values tothe desired data type.A single-row subquery from a table or tables is not considered a constant. For example, if a subqueryreturns an integer to be compared to a DATETIME value, the comparison is done as two integers.The integer is not converted to a temporal value. To compare the operands as DATETIME values,use CAST() to explicitly convert the subquery value to DATETIME.6、If one of the arguments is a decimal value, comparison depends on the other argument. Thearguments are compared as decimal values if the other argument is a decimal or integer value, or asfloating-point values if the other argument is a floating-point value.7、In all other cases, the arguments are compared as floating-point (real) numbers.

参考文章

1、聊聊 隐式转换

2、Type Conversion in Expression Evaluation:https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html

感谢八怪的友情指导,想学习更多源码内容,强烈推荐一下八怪的专栏《深入理解MySQL主从原理》

END


点击下图小程序订阅

《深入理解MySQL主从原理32讲》专栏

可了解更多八怪技术文章

知数堂

这里有好课,为职场助攻

免费兑换知数堂的课程和周边,戳此了解

现招聘课程销售助理数枚

不限地区,不限年龄

若您懂“数”又自带流量

欢迎投简历加入我们

扫码了解岗位详情

扫码加入MySQL技术Q群

(群号:793818397)

在将varchar值id转换为int时失败_MySQL令人咋舌的隐式转换相关推荐

  1. 在将varchar值id转换为int时失败_C++繁琐的类型转换,C++小知识之四种类型转换

    有时,编程的过程中需要将值从一种数据类型转换为另一种数据类型. 在C语言中,强制类型转换的方式为(Type)Expression,另外还有一种现在已经不用的旧式写法Type(Expression),这 ...

  2. 在将varchar值id转换为int时失败_Python—CAN报文转换工具教程

    一.CAN报文简介 CAN是控制器局域网络(Controller Area Network, CAN)的简称,是由以研发和生产汽车电子产品著称的德国BOSCH公司开发的,并最终成为国际标准(ISO 1 ...

  3. js return的值取不到_【JS基础】隐式转换(一)

    开篇 JS作为一门动态语言十分灵活,但是伴随而来的弱类型隐式转化的问题让我们十分头疼. 隐式作为一个大课题,很难用一个很简短的篇幅把JS的隐式转换讲解的十分清楚.所以我选择用多次少量的策略进行梳理,争 ...

  4. 消息 245,级别 16,状态 1,第 1 行 在将 varchar 值 '2,8' 转换成数据类型 int 时失败。...

    错误问题: 消息 245,级别 16,状态 1,第 1 行 在将 varchar 值 '2,8' 转换成数据类型 int 时失败. ps: 这是在后台分配菜单权限这个功能时出现的问题 一,解决方法: ...

  5. 将 varchar 值 'ACCE5057EC423F7C' 转换成数据类型 int 时失败

    调试别人的存储过程,然后报错了 将 varchar 值 'ACCE5057EC423F7C' 转换成数据类型 int 时失败 这让我一通找.找了一个多小时. 通过这个错可以知道,错误肯定是在联表 字段 ...

  6. 佩特来项目经验小集合(2)___组合查询存储过程,报错 quot;varchar JBID=#39;#39; 转换成数据类型 int 时失败quot;...

       今天写一个组合查询的存储过程遇到这样一个问题:在将 varchar 值 'SELECT * FROM View_DLS_WXJD_Customer WHERE 1=1 and JBID ='' ...

  7. mysql in 数字类型_关于sql where id in 转换成数据类型 int 时失败

    有执行sql条件语句where id in(@参数)的时候,如果处理不当,就会出现问题: 有执行sql条件语句where id in(@参数)的时候,如果处理不当,就会出现问题: 如下面这个存储过程: ...

  8. 异常处理·MSSQL·在将nvarchar值‘XXX‘转换成数据类型int时失败

    阅文时长 | 0.16分钟 字数统计 | 260.8字符 主要内容 | 1.引言&背景 2.声明与参考资料 『异常处理·MSSQL·在将nvarchar值'XXX'转换成数据类型int时失败』 ...

  9. 无法将类型int隐式转换为string_Scala implicit 隐式转换安全驾驶指南

    这篇短文将结合实例对隐式转换的各种场景进行解释和总结,希望看完的人能够安全驶过隐式转换这个大坑. 隐式转换函数 隐式转换函数有两种作用场景. 1 转换为期望类型:就是指一旦编译器看到X,但需要Y,就会 ...

最新文章

  1. 用gdb调试core dump文件
  2. 数据库 文件 备份【学习 使用】
  3. 解读:在什么业务场景适合使用Redis?
  4. 不安装cudnn可不可以_Linux非root用户如何优雅的安装cuda和cudnn
  5. C语言精髓篇|函数的参数和返回值
  6. linux系统查看分区文件系统
  7. nodejs+express- http 访问本地json数据
  8. 控制系统数字仿真-基于MATLAB实现四阶龙格库塔法
  9. 2016计算机考研经验,2016届浙大计算机考研复习经验整理
  10. STM32F107RBT6移植freeRTOS
  11. Moldflow 2018模流分析从入门到精通pdf txt mobi读书笔记
  12. 融资2500万美元,#Spatial从协作办公进化到元宇宙产品,#NFT创作生态
  13. 汽车芯片:缺货将诱发产业变革
  14. B站Django项目天天生鲜学习|celery异步发送邮件遇到的问题
  15. 中国科学院大学计算机考研好考吗,中国科学院大学考研难吗?一般要什么水平才可以进入?...
  16. 在 Node.js 应用中集成 Redis
  17. 开始CentOS世界 从yum搭建lnmp环境开始,root的密码破解,定时任务, 后续其他功能 redHat5.4
  18. oauth2-怎么使用
  19. 计算机动画 vr技术应用,三维动画与VR交互和虚拟现实性技术的结合
  20. 骨龄预测系列---番外篇

热门文章

  1. leetcode 寻找两个有序数组的中位数
  2. 【服务端渲染】手动部署 NuxtJs 项目
  3. PLSQL Developer连接数据库报错ora-12514解决
  4. 利用Gitee搭建个人图床(上)
  5. 正则语言和正则表达式_探索正则表达式背后的语言学
  6. c语言二分法_14个经典C语言算法你就不看一眼?(附详细代码)
  7. 怎么关闭电脑开机自动启动的程序_软件自动开启很烦人?如何彻底关掉Mac电脑开机自动开启的应用程序?...
  8. 非常实用的Python库
  9. AI朋克致敬MNIST:只用Python和开发板,制作永不重样的时钟
  10. 本地Spark连接远程集群Hive(Scala/Python)