简体   繁体   English

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

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

I have the following table: 我有下表:

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)
);   

If I EXPLAIN the query 如果我解释查询

select id from stuff order by id;

then it says it uses they primary key as an index for ordering the results. 然后它说它使用主键作为排序结果的索引。 But with this query: 但是有了这个查询:

select id,title from stuff order by id;

EXPLAIN says no possible keys and it resorts to filesort. EXPLAIN说没有可能的密钥,它会转向filesort。

Why is that? 这是为什么? Isn't the data of a certain row stored together in the database? 是不是某个行的数据一起存储在数据库中? If it can order the results using the index when I'm querying only the id then why adding an other column to the query makes a difference? 如果我只查询id时可以使用索引对结果进行排序,那么为什么在查询中添加其他列有所不同? The primary key identifies the row already, so I think it should use the primary key for ordering in the second case too. 主键已经标识了行,所以我认为在第二种情况下它应该使用主键进行排序。

Can you explain why this is not the case? 你能解释一下为什么不是这样吗?

Sure, because it is more performant in this query: you need to read full index and after that iteratively read row by row from data. 当然,因为它在此查询中更具性能:您需要读取完整索引,然后迭代地逐行读取数据。 This is extremely unefficient. 这非常低效。 Instead of this mysql just prefers to read the data right from the data file. 而不是这个mysql只是更喜欢从数据文件中读取数据。

Also, what kind of storage engine do you use? 另外,您使用什么样的存储引擎? Seems like mysam. 好像是mysam。

For this case innodb would be more efficient, since it uses clustered indexes over primary key (which is monotonously growing in your case). 对于这种情况,innodb会更有效率,因为它使用主键上的聚簇索引(在您的情况下单调增长)。

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

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