mysql 1313_MySQL 类型转换引发的慢查询

MySQL 类型转换引发的慢查询

首先上一段Mysql官方文档:

The following rules describe how conversion occurs for comparison operations:

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.

这段文档对数据比较环境下的数据类型转换规则做了详细介绍,翻译过来就是:

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

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

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

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

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

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

根据以上的说明,当where条件之后的值的类型和表结构不一致(int与varchar类型作比较)的时候,MySQL会做隐式的类型转换,都将其转换为浮点数在比较。

下面以两个例子具体说明,例子一:

5a4991e54cbb252a52dbd202c1dcfb8f.png

从上面可以很明显的看到由于appkey是varchar,而在where条件中不加'',需要将索引中的字符串转换成浮点数,但是由于'1',' 1','1a'都会比转化成1,故MySQL无法使用索引只能进行全表扫描,加了就可以用到索引,这扫描的行数可是天差地别,对于服务器的压力和响应时间自然也是天差地别的。

例子二:

1d58ef1d305c171c76f662857ba45274.png

虽然poll_id的类型为bigint,但是SQL中添加了'',但是这个语句仍然用到了索引,因为索引建立在int的基础上,而将纯数字的字符串可以百分百转换成数字,故可以使用到索引,虽然也会进行一定的转换,消耗一定的资源,但是最终仍然使用了索引,不会产生慢查询,虽然扫描行数也不少,但是能用到索引就是好SQL。

同时还有一点需要注意:int,varchar进行比较都会转换成浮点数进行比较,而浮点数只有53bit,故当超过最大值的时候,比较会出现问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值