简体   繁体   English

如何避免此 mysql 查询的文件排序

[英]How to avoid filesort for this mysql query

I need some help in avoiding filesort for this query.我需要一些帮助来避免对这个查询进行文件排序。

  SELECT id 
    FROM articles USE INDEX(group)
   WHERE type = '4' 
     AND category = '161' 
     AND did < '10016' 
     AND id < '9869788' 
ORDER BY id DESC 
   LIMIT 10

INDEX(group) is a covering index of ( type , category , did , id ) INDEX(group) 是 ( type , category , did , id ) 的覆盖索引

Because of ORDER BY id DESC , filesort is performed.由于ORDER BY id DESC ,执行文件排序。 Is there a way to avoid filesort for such query?有没有办法避免对此类查询进行文件排序?

Change the index column order.更改索引列顺序。 The index is useless for the sort because it'^s the 4th column and isn't ready to be used as-is.该索引对排序没有用处,因为它是第 4 列并且还没有准备好按原样使用。

Of course, this affects the usefulness of the index for this WHERE because you need an inequality column before an equality one当然,这会影响索引对这个 WHERE 的有用性,因为在相等列之前需要一个不等列

In the MySQL docs , you break "You use ORDER BY on nonconsecutive parts of a key" and "The key used to fetch the rows is not the same as the one used in the ORDER BY"MySQL 文档中,您打破了“您在键的非连续部分上使用 ORDER BY”和“用于获取行的键与 ORDER BY 中使用的键不同”

Edit: as per my link above, you can't have an index that satisfies both WHERE and ORDER BY.编辑:根据我上面的链接,您不能拥有同时满足 WHERE 和 ORDER BY 的索引。 They are mutually exclusive because of the 2 conditions I posted above由于我在上面发布的两个条件,它们是互斥的

Another suggestion:另一个建议:

  • a single column index on id id 上的单列索引
  • go back to the original index too go 也回到原来的索引
  • remove the index hint删除索引提示
  • hope that the optimiser works out that both indexes can be used ("index intersection")希望优化器解决两个索引都可以使用(“索引交集”)

Create index on id and type it should work for you.在 id 上创建索引并键入它应该适合您。 If Id is unique you can also create the Primary Key for it.如果 Id 是唯一的,您还可以为其创建主键。

your query is using file sort because it might be possible that the optimizer is using the first column of index you created in the query.您的查询正在使用文件排序,因为优化器可能正在使用您在查询中创建的索引的第一列。

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

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