MySQL: Explain Plan中的Using Index意思是用到了Covering Index

看下下面这条语句的explain plan  (user_name已被索引)

select user_name from user where user_name = 'chenjianjx' 

你会发现 Extra这一列中写的是:Using Index

它的意思执行查询时用到了Covering Index. 

Covering Index的意思是指索引中直接包含了一个查询所需返回的数据。按user_name只查user_name, 所有数据都可以从user_name的索引中给出。

很明显,这对性能有帮助,因为你不需要再费几次I/O去取数据; 同时由于索引本身排好了序,体积小更容易直接存储在内存中,所以只查索引,性能上的好处是很大的。

如果查整行,

select * from user where user_name = 'chenjianjx' 

Extra中就不再有"Using Index"了,因为你的索引中本身没有存储整行。

如果你的存储引擎是Innodb, 这样查呢?

select id, user_name from user where user_name = 'chenjianjx'   -- id是主键

Extra中又会有"Using Index", 这是因为在innodb中,所有secondary index中的结点中都包含了相应数据对应的主键的值。

以上结论的作用是:不要总是傻傻地返回整行( select *) . 如果你直需要索引中的数据,或者索引中的数据加上主键(只对innodb有效),那就让你的sql只返回索引字段吧(以及主键)。

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.