【转】MySQL int转换成varchar引发的慢查询
转自http://www.cnblogs.com/billyxp/archive/2013/05/31/3110016.html
最近一周接连处理了2个由于int向varchar转换无法使用索引,从而引发的慢查询。

CREATE TABLE `appstat_day_prototype_201305` (
`day_key` date NOT NULL DEFAULT '1900-01-01',
`appkey` varchar(20) NOT NULL DEFAULT '',
`user_total` bigint(20) NOT NULL DEFAULT '0',
`user_activity` bigint(20) NOT NULL DEFAULT '0',
`times_total` bigint(20) NOT NULL DEFAULT '0',
`times_activity` bigint(20) NOT NULL DEFAULT '0',
`incr_login_daily` bigint(20) NOT NULL DEFAULT '0',
`unbind_total` bigint(20) NOT NULL DEFAULT '0',
`unbind_activitys` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`appkey`,`day_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 mysql> explain SELECT * from appstat_day_prototype_201305 where appkey = xxxxx and day_key between '2013-05-23' and '2013-05-30';
+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+
| 1 | SIMPLE | appstat_day_prototype_201305 | ALL | PRIMARY | NULL | NULL | NULL | 19285787 | Using where |
+----+-------------+------------------------------+------+---------------+------+---------+------+----------+-------------+
1 row in set (0.00 sec) mysql> explain SELECT * from appstat_day_prototype_201305 where appkey = 'xxxxx' and day_key between '2013-05-23' and '2013-05-30';
+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+
| 1 | SIMPLE | appstat_day_prototype_201305 | range | PRIMARY | PRIMARY | 65 | NULL | 1 | Using where |
+----+-------------+------------------------------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.00 sec)

从上面可以很明显的看到由于appkey是varchar,而在where条件中不加'',会引发全表查询,加了就可以用到索引,这扫描的行数可是天差地别,对于服务器的压力和响应时间自然也是天差地别的。
我们再看另外一个例子:

*************************** 1. row ***************************
Table: poll_joined_151
Create Table: CREATE TABLE `poll_joined_151` (
`poll_id` bigint(11) NOT NULL,
`uid` bigint(11) NOT NULL,
`item_id` varchar(60) NOT NULL,
`add_time` int(11) NOT NULL DEFAULT '0',
`anonymous` tinyint(1) NOT NULL DEFAULT '0',
`sub_item` varchar(1200) NOT NULL DEFAULT '',
KEY `idx_poll_id_uid_add_time` (`poll_id`,`uid`,`add_time`),
KEY `idx_anonymous_id_addtime` (`anonymous`,`poll_id`,`add_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 SELECT * FROM poll_joined_151 WHERE poll_id = '2348993' AND anonymous =0 ORDER BY add_time DESC LIMIT 0 , 3 *************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: poll_joined_151
type: ref
possible_keys: idx_poll_id_uid_add_time,idx_anonymous_id_addtime
key: idx_anonymous_id_addtime
key_len: 9
ref: const,const
rows: 30240
Extra: Using where

从上面的例子看,虽然poll_id的类型为bigint,但是SQL中添加了'',但是这个语句仍然用到了索引,虽然扫描行数也不少,但是能用到索引就是好SQL。
那么一个小小的''为什么会有这么大的影响呢?根本原因是因为MySQL在对文本类型和数字类型进行比较的时候会进行隐式的类型转换。以下是5.5官方手册的说明:

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.
有一个参数是 TIMESTAMP 或 DATETIME,并且另外一个参数是常量,常量会被转换为 timestamp
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.
有一个参数是 decimal 类型,如果另外一个参数是 decimal 或者整数,会将整数转换为 decimal 后进行比较,如果另外一个参数是浮点数,则会把 decimal 转换为浮点数进行比较
In all other cases, the arguments are compared as floating-point (real) numbers.
所有其他情况下,两个参数都会被转换为浮点数再进行比较

根据以上的说明,当where条件之后的值的类型和表结构不一致的时候,MySQL会做隐式的类型转换,都将其转换为浮点数在比较。
对于第一种情况:
比如where string = 1;
需要将索引中的字符串转换成浮点数,但是由于'1',' 1','1a'都会比转化成1,故MySQL无法使用索引只能进行全表扫描,故造成了慢查询的产生。

mysql> SELECT CAST(' 1' AS SIGNED)=1;
+-------------------------+
| CAST(' 1' AS SIGNED)=1 |
+-------------------------+
| 1 |
+-------------------------+
1 row in set (0.00 sec) mysql> SELECT CAST(' 1a' AS SIGNED)=1;
+--------------------------+
| CAST(' 1a' AS SIGNED)=1 |
+--------------------------+
| 1 |
+--------------------------+
1 row in set, 1 warning (0.00 sec) mysql> SELECT CAST('1' AS SIGNED)=1;
+-----------------------+
| CAST('1' AS SIGNED)=1 |
+-----------------------+
| 1 |
+-----------------------+
1 row in set (0.00 sec)

同时需要注意一点,由于都会转换成浮点数进行比较,而浮点数只有53bit,故当超过最大值的时候,比较会出现问题。
对于第二种情况:
由于索引建立在int的基础上,而将纯数字的字符串可以百分百转换成数字,故可以使用到索引,虽然也会进行一定的转换,消耗一定的资源,但是最终仍然使用了索引,不会产生慢查询。

mysql> select CAST( '30' as SIGNED) = 30;
+----------------------------+
| CAST( '30' as SIGNED) = 30 |
+----------------------------+
| 1 |
+----------------------------+
1 row in set (0.00 sec)

【转】MySQL int转换成varchar引发的慢查询的更多相关文章
- SQL中DateTime转换成Varchar样式
SQL中DateTime转换成Varchar样式语句及查询结果:Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AMSelect ...
- MySql Int 类型和 varchar类型进行比较。
今天遇到个比较奇葩的问题,简单讲就是在Mysql中进行查询的时候 在Where语句中使用的int类型的字段和Varchar类型的字段进行对比. 例如:我这有一张表: 表中的数据如下: 当我进行查询的时 ...
- C#中如何把int转换成两个字符的string
部门新开了项目,所以一整周的时间都在瞎忙,为什么称瞎忙?所负责的内容,并没有做好,也是一万个心塞啊.... 说一下最近碰到的一些问题. 用到了计时,但是比如定时是一分半钟,可是显示的时候,想让显示为1 ...
- flask框架下读取mysql数据 转换成json格式API
研究了一天 因为需要从数据库拿数据然后转换成json的格式 expose出去为 API 发现一条数据是容易,两条以上我居然搞了这么久 好歹出来了 先贴一下 后面更新 mysql的操作 比较容易了htt ...
- Mysql 表转换成 Sqlite表
目前的转换仅仅支持对没有外键的Mysql数据表 准备: 下载安装 Sqlite Expert 软件 一 获取Mysql中的.sql文件,获取过程省略可以直接导出sql文件 二 在Sqlite Expe ...
- mysql时间戳转换成可读时间格式
代码: SELECT FROM_UNIXTIME(1234567890, '%Y-%m-%d %H:%i:%S') 附:在mysql中,一个时间字段的存储类型是int(11),怎么转化成字符类型,比方 ...
- SqlServer将日期格式DateTime转换成varchar类型
Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AM Select CONVERT(varchar(100), GETDATE( ...
- int 转换成 CString(VC2008里有这个问题)
int s = 123; CString str; str.Format("%d",s); 这样就可以了,但是有的会提示这个错误 如果出现这个错误,就改成下面这个就OK了: st ...
- MySQL中文转换成拼音的函数
CREATE DEFINER=`root`@`localhost` FUNCTION `fristPinyin`(`P_NAME` VARCHAR(255) CHARSET utf8) RETURNS ...
随机推荐
- 并发服务器--02(基于I/O复用——运用epoll技术)
本文承接自上一博文I/O复用——运用Select函数. epoll介绍 epoll是在2.6内核中提出的.和select类似,它也是一种I/O复用技术,是之前的select和poll的增强版本. Li ...
- Android ROM开发(三)——精简官方ROM并且内置ROOT权限,开启Romer之路
Android ROM开发(三)--精简官方ROM并且内置ROOT权限,开启Romer之路 相信ROM的相关信息大家通过前几篇的学习都是有所了解了,这里就不在一一提示了,这里我们下载一个官方包,我们还 ...
- Gradle 1.12用户指南翻译——第三十四章. JaCoCo 插件
本文由CSDN博客万一博主翻译,其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Githu ...
- 数据包接收系列 — NAPI的原理和实现
本文主要内容:简单分析NAPI的原理和实现. 内核版本:2.6.37 Author:zhangskd @ csdn 概述 NAPI是linux新的网卡数据处理API,据说是由于找不到更好的名字,所以就 ...
- java--交通灯管理系统
转载请申明出处:http://blog.csdn.net/xmxkf/article/details/9944947 .交通灯管理系统的业务和需求分析 交通灯管理系统的项目需求: 模拟实现十字路口的交 ...
- C#中使用双缓冲来避免绘制图像过程中闪烁
自己所做项目中,在显示医学图像的界面中,当鼠标拖动图像时,不断刷新从后台获取新的图像,而整个过程就很诡异,一直闪个不停. 找到的一个可行方法是:在用户控件的构造函数中加入以下代码: SetStyle( ...
- angularjs作用域之transclude
transclude是一个可选的参数.如果设置了,其值必须为true,它的默认值是false.嵌入有时被认为是一个高级主题,但某些情况下它与我们刚刚学习过的作用域之间会有非常好的配合.使用嵌入也会很好 ...
- javax.mail
摘抄 example: public static void sendEmail(ConfBean cBean, String filename, String filepath) { try { P ...
- tomcat 工作原理
Tomcat原理 分类: TOMCAT2009-05-17 22:25 4366人阅读 评论(3) 收藏 举报 tomcatexceptionsocketstringservernull Tomcat ...
- IntelliJ IDEA下Cannot resolve symbol XXX的解决方法
Idea导入maven项目后,运行能通过,但是打开一些类后,会出现Cannot resolve symbol XXX的错误提示. 考虑几种可能: 1.JDK版本,设置JDK和Maven的JDK版本. ...