索引 - MySQL limit对效率的影响
怪我咯
怪我咯 2017-04-17 13:04:14
[MySQL讨论组]

有一张很老的数据表,时间戳格式为varchar,字段如下:

id bigint
name varchar(200)
create_time varchar(200)
//索引
KEY `IDX_CREATED` (`create_time`),

数据约500多万,现在引出发现的问题,一条sql语句效率非常的低:

select id, name from t where create_time > 1434115807296 order by create_time limit 1000;

本机测试200s,执行计划:

> explain select id, name from t where create_time > 1434115807296 order by create_time limit 1000;

+----+-------------+-------+-------+---------------+---------------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key           | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+-------------+
|  1 | SIMPLE      | User  | index |  IDX_CREATED  |  IDX_CREATED  |   63    | NULL | 1000 | Using where |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+-------------+
1 row in set (0.00 sec)

如果去掉 limit :

select id, name from t where create_time > 1434115807296 order by create_time

执行时间5s,执行计划:

> explain select id, name from t where create_time > 1434115807296 order by create_time

+----+-------------+-------+------+---------------+------+---------+------+---------+-----------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows    | Extra                       |
+----+-------------+-------+------+---------------+------+---------+------+---------+-----------------------------+
|  1 | SIMPLE      | User  | ALL  |  IDX_CREATED  | NULL |   NULL  | NULL | 4858500 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+---------+-----------------------------+
1 row in set (0.00 sec)    

一个 index 查询竟然比 ALL&filesort 查询慢这么多? 请 MySQL 达人指教

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
PHP中文网

看执行计划,这两个差别主要在于是否使用了IDX_CREATED的索引,以及filesort。

前者用上了索引,所以你前面where条件的查询速度会有很大提高,但是很奇怪没有用到filesort,所以在后面的order by阶段会消耗了很大的时间。

后者就是直接简单的查询,没有使用索引,并进行了正常的文件排序。

可以考虑强制不使用索引Ignore index来优化此句的性能。
建议你用profile跟踪再详细看一下每个阶段的时间消耗,这样会更为准确。

PHP中文网


create_time varchar(200)
改为
create_time int(11)

你是用laravel框架自动生成的吧?傻!

另外,你这样对比不公平啊!
MYSQL 分页慢加速器 解决方案 MYSQL 分页优化 MYSQL 分页解决方案 LIMIT 优化

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号