简体   繁体   English

MySQL何时将对使用order by子句的查询应用索引条件推送?为什么?

[英]When will MySQL apply Index Condition Push for a query with order by clause?Why?

I have an article table with a multi column index (author_id, reply_time, id). 我有一个带有多列索引(author_id,reply_time,id)的文章表。

explain select * from article where author_id=3658768 and reply_time>'2015-01-01' and id>85669107 order by reply_time
explain select * from article where author_id=3658768 and reply_time>'2015-01-01' and id<85669107 order by reply_time
explain select * from article where author_id=3658768 and reply_time<'2015-01-01' and id>85669107 order by reply_time
explain select * from article where author_id=3658768 and reply_time<'2015-01-01' and id<85669107 order by reply_time

will use Index Condition Push (the "extra" field of explain output is "Using index condition") 将使用索引条件推送(说明输出的“额外”字段为“使用索引条件”)

However, all queries as follows will not use Index Condition Push (the "extra" field of explain output is "Using where") 但是,以下所有查询将不使用索引条件推送(explain输出的“ extra”字段为“ Using where”)

explain select * from article where author_id=3658768 and reply_time>'2015-01-01' and id>85669107 order by reply_time desc
explain select * from article where author_id=3658768 and reply_time>'2015-01-01' and id<85669107 order by reply_time desc
explain select * from article where author_id=3658768 and reply_time<'2015-01-01' and id>85669107 order by reply_time desc
explain select * from article where author_id=3658768 and reply_time<'2015-01-01' and id<85669107 order by reply_time desc

Does MySQL use Index Condition Push only for order by asc? MySQL是否仅按索引顺序使用索引条件推送?

There is little sense in having an index by author_id, reply_time, id unless you're certain that there will be several id s for the same author_id, reply_time . 通过author_id, reply_time, id进行索引几乎没有意义author_id, reply_time, id除非您确定同一author_id, reply_time会有多个id The index will be no better than being by author_id, reply_time alone. 索引不会比仅通过author_id, reply_timeauthor_id, reply_time更好。

You'd be better off with two indexes, one by author_id, reply_time and another by author_id, id , and the planner will use the index that is most likely (from collected statistics) that will render the fewer number of rows that have to be sequentially filtered. 您最好使用两个索引,一个通过author_id, reply_time和另一个通过author_id, id索引,并且计划者将使用最有可能(从收集的统计数据中)得出的索引数量将减少的行数。按顺序过滤。

Whether the sort is ascending or descending is irrelevant, the planner can make use of an index for sorting, it can use it both for ascending or descending equally well. 不管排序是升序还是降序都是无关紧要的,计划者可以利用索引进行排序,也可以很好地使用它进行升序或降序。 But sometimes it just can't use it at all, or it's most expensive using it that sorting the rowset. 但是有时它根本无法使用它,或者使用它对行集进行排序最昂贵。

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

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