为什么当我查询更多列时,MYSQL 不使用同一查询的索引?
我有下表:
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 说没有可能的键,它求助于文件排序。
这是为什么?数据库中不是把某一行的数据存储在一起吗?如果当我只查询 id 时它可以使用索引对结果进行排序,那么为什么向查询添加其他列会产生影响呢?主键已经标识了行,所以我认为在第二种情况下也应该使用主键进行排序。
你能解释一下为什么情况并非如此吗?
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.
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? 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,因为它在此查询中性能更高:您需要读取完整索引,然后从数据中逐行迭代读取。这是极其低效的。相反,mysql 更喜欢直接从数据文件中读取数据。
另外,你使用什么样的存储引擎?看起来像米萨姆。
对于这种情况,innodb 会更有效,因为它使用主键上的聚集索引(在您的情况下单调增长)。
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.
Also, what kind of storage engine do you use? Seems like mysam.
For this case innodb would be more efficient, since it uses clustered indexes over primary key (which is monotonously growing in your case).