隐式转换引起sql慢查询的示例分析

46次阅读
没有评论

共计 2045 个字符,预计需要花费 6 分钟才能阅读完成。

丸趣 TV 小编给大家分享一下隐式转换引起 sql 慢查询的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

引言

实在很无语呀,遇到一个 mysql 隐式转换问题,问了周边的 dba 大拿该问题,他们居然反问我,你连这个也不知道?白白跟他们混了那么长   尼玛,我还真不知道。罪过罪过…. 

问题是这样的,一个字段叫 task_id, 本身是 varchar 字符串类型,但是因为老系统时间太长了,我以为是 int 或者 bigint,所以直接在代码写 sql 跑数据,结果等了好久就是没有反应,感觉要坏事呀。在 mysql processlist 里看到了该 sql 语句,直接 kill 掉。该字段是有索引的,并且他的 sql 选择性很高,索引的价值也高。但为什么这么慢?

分析问题

通过 explain 分析出了结果,当使用整型来查询字符串的字段会出现无法走索引的情况,看下面可以知道,key 为 NULL,没走索引,Rows 是很大的数值,基本是全表扫描了。  当正常的用字符串查询字符串就很正常了,索引没问题,rows 的值为 1,这里说的是扫描聚簇索引的 rows,而不是索引二级索引。

那么为什么会出现这问题?

下面是 mysql 官方给出的说法,最后一条很重要,当在其他情况下,两个参数都会统一成 float 来比较。居然新版的 mysql 在优化器层面已经做了一些调整规避这问题,但我自己的测试版本是 mysql 5.6,阿里云用的也是 5.7,都没有解决该问题。看来是更高版本解决吧,这个待验证。

看完了官方解说,我们知道上面那一句慢查询 sql,其实就相当于 where to_int(taskid) = 516006380。当然直接用 to_int 是显示转换了,但是对比出来的效果是一致的。  不管是隐式转换,还是显示转换,速度能起来才怪。。。因为 mysql 不支持函数索引。

# xiaorui.cc
 
If both arguments in a comparison operation are strings, they are compared as strings.
If both arguments are integers, they are compared as integers.
Hexadecimal values are treated as binary strings if not compared to a number.
If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. Note that this is not done for the arguments to IN()! To be safe, always use complete datetime, date, or time strings when doing comparisons. For example, to achieve best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type.
If one of the arguments is a decimal value, comparison depends on the other argument. The arguments are compared as decimal values if the other argument is a decimal or integer value, or as floating-point values if the other argument is a floating-point value.
In all other cases, the arguments are compared as floating-point (real) numbers.

翻译为中文就是:

两个参数至少有一个是 NULL 时,比较的结果也是 NULL,例外是使用 = 对两个 NULL 做比较时会返回 1,这两种情况都不需要做类型转换

两个参数都是字符串,会按照字符串来比较,不做类型转换

两个参数都是整数,按照整数来比较,不做类型转换

十六进制的值和非数字做比较时,会被当做二进制串

有一个参数是 TIMESTAMP 或 DATETIME,并且另外一个参数是常量,常量会被转换为 timestamp

有一个参数是 decimal 类型,如果另外一个参数是 decimal 或者整数,会将整数转换为 decimal 后进行比较,如果另外一个参数是浮点数,则会把 decimal 转换为浮点数进行比较

所有其他情况下,两个参数都会被转换为浮点数再进行比较

看完了这篇文章,相信你对“隐式转换引起 sql 慢查询的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注丸趣 TV 行业资讯频道,感谢各位的阅读!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-04发表,共计2045字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)