暂无图片
mysql创建索引后,没有使用上,explain仍然显示:Using filesort
我来答
分享
暂无图片 匿名用户
mysql创建索引后,没有使用上,explain仍然显示:Using filesort

create table `test1` (
`id` int not null auto_increment,
`videoid` int not null default 0,
`memid` int not null default 0,
primary key (`id`),
key `idx_videoid` (`videoid`)


插入1000条测试数据,

最开始


mysql> explain select * from test1 order by memid\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test1
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
filtered: 100.00
Extra: Using filesort


后来在memid 字段上创建索引之后,

mysql> show index from test1;
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| test1 | 0 | PRIMARY | 1 | id | A | 1000 | NULL | NULL | | BTREE | | | YES | NULL |
| test1 | 1 | idx_videoid | 1 | videoid | A | 1000 | NULL | NULL | | BTREE | | | YES | NULL |
| test1 | 1 | idx_memid | 1 | memid | A | 1000 | NULL | NULL | | BTREE | | | YES | NULL |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+----


mysql> analyze table test1;
+------------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+------------+---------+----------+----------+
| test.test1 | analyze | status | OK |
+------------+---------+----------+----------+
1 row in set (0.04 sec)

mysql> explain select * from test1 order by memid\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test1
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
filtered: 100.00
Extra: Using filesort

收集统计信息之后,怎么还是Using filesort ,并且索引也没有使用上?

我来答
添加附件
收藏
分享
问题补充
2条回答
默认
最新
lianR

MySQL的排序有两种方式,一种是通过索引直接返回有序的结果集,另一种是通过文件排序(filesort)返回结果集。

在你的例子中,虽然你在memid字段上创建了索引,但是你的查询是“select  *”,也就是选择所有字段,这就导致了索引无法被使用。因为索引存储的是字段的值和这些值在表中的位置,如果查询的字段超过了索引的字段,那么MySQL就需要去原表中查找数据,这就导致了索引失效。

而且,你的查询语句中使用了order  by,这就需要MySQL进行排序。如果能通过索引直接返回有序的结果集,那么就不需要排序。但是在这个例子中,索引无法被使用,所以MySQL只能通过文件排序(filesort)来返回有序的结果集。

所以,如果你想让索引生效,你可以尝试只选择索引字段,比如“select  memid  from  test1  order  by  memid”,这样MySQL就可以通过索引直接返回有序的结果集,不需要进行文件排序。

暂无图片 评论
暂无图片 有用 1
everything

1、假设使用idx_memid索引获取数据,需要遍历idx_memid,再根据主键id回表查询;最终需要扫描两个索引树。
2、根据主键访问只需扫描一次全表后,内存排序。
1比2需要的io次数多一倍,io和memory的cost至少相差一个量级。肯定选2执行了。

暂无图片 评论
暂无图片 有用 1
回答交流
提交
问题信息
请登录之后查看
邀请回答
暂无人订阅该标签,敬请期待~~
暂无图片墨值悬赏