繁体   English   中英

如果我查询更多列,为什么MYSQL不对同一查询使用索引?

[英]Why MYSQL doesn't use the index for the same query if I query more columns?

我有下表:

create table stuff (
       id mediumint unsigned not null auto_increment primary key,
       title varchar(150) not null,
       link varchar(250) not null,
       time timestamp default current_timestamp not null,
       content varchar(1500)
);   

如果我解释查询

select id from stuff order by id;

然后它说它使用主键作为排序结果的索引。 但是有了这个查询:

select id,title from stuff order by id;

EXPLAIN说没有可能的密钥,它会转向filesort。

这是为什么? 是不是某个行的数据一起存储在数据库中? 如果我只查询id时可以使用索引对结果进行排序,那么为什么在查询中添加其他列有所不同? 主键已经标识了行,所以我认为在第二种情况下它应该使用主键进行排序。

你能解释一下为什么不是这样吗?

当然,因为它在此查询中更具性能:您需要读取完整索引,然后迭代地逐行读取数据。 这非常低效。 而不是这个mysql只是更喜欢从数据文件中读取数据。

另外,您使用什么样的存储引擎? 好像是mysam。

对于这种情况,innodb会更有效率,因为它使用主键上的聚簇索引(在您的情况下单调增长)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM