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

发布于 2024-11-19 08:00:22 字数 408 浏览 2 评论 0原文

我需要一些帮助来避免此查询的文件排序。

  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) 是 (type, category, did, id) 的覆盖索引,

因为 ORDER BY id DESC,执行文件排序。有没有办法避免此类查询的文件排序?

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)

Because of ORDER BY id DESC, filesort is performed. Is there a way to avoid filesort for such query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

司马昭之心 2024-11-26 08:00:22

更改索引列顺序。该索引对于排序来说是无用的,因为它是第四列,并且还没有准备好按原样使用。

当然,这会影响该 WHERE 索引的有用性,因为

MySQL 文档,你打破了“你在键的非连续部分使用 ORDER BY”和“用于获取行的键与使用的键不同”在订单中BY”

编辑:根据我上面的链接,您不能拥有同时满足 WHERE 和 ORDER BY 的索引。由于我上面发布的两个条件,它们是互斥的

另一个建议:

  • id上的单列索引
  • 也返回到原始索引
  • 删除索引提示
  • 希望优化器计算出两个索引都可以使用(“索引交集”)

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.

Of course, this affects the usefulness of the index for this WHERE because you need an inequality column before an equality one

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"

Edit: as per my link above, you can't have an index that satisfies both WHERE and ORDER BY. They are mutually exclusive because of the 2 conditions I posted above

Another suggestion:

  • a single column index on id
  • go back to the original index too
  • remove the index hint
  • hope that the optimiser works out that both indexes can be used ("index intersection")
<逆流佳人身旁 2024-11-26 08:00:22

在 id 上创建索引并输入它应该适合您。
如果 Id 是唯一的,您还可以为其创建主键。

您的查询正在使用文件排序,因为优化器可能正在使用您在查询中创建的索引的第一列。

Create index on id and type it should work for you.
If Id is unique you can also create the Primary Key for it.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文