让 SQL 使用正确的索引

发布于 2024-07-23 04:42:23 字数 144 浏览 0 评论 0原文

我有一个包含两个索引的表,其中一个是特定查询的更快覆盖索引。 然而,mySQL (5.1) 没有选择正确的索引。 我已经查看了这个查询的解释并做了一些速度测试,如果你强制按键,它会产生很大的差异。

有没有办法检查它如何选择指数以及它基于什么标准?

I have a table with two indexes, one of which is the faster covering index for a certain query. However, mySQL (5.1) is not choosing the correct index. I have looked at the explain for this query and done some speed tests and it makes a big difference if you force the key.

Is there any way of examining how it picks the index and what criteria it is basing this on?

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

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

发布评论

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

评论(1

茶花眉 2024-07-30 04:42:23

这将使用您需要的索引(如果它可用):

SELECT  *
FROM    table FORCE INDEX (myindex)

MySQL 收集并使用表统计信息来估计索引的基数。

它将其保存在information_schema.statistics中。

在可用于过滤的两个索引中,MySQL 选择基数较大的一个。

如果有两个基数较大的索引,则可以对这两个索引选择INDEX MERGE

在一个索引可以提供 WHERE 条件,另一个索引可以提供 ORDER BY 条件时,MySQL 似乎更喜欢第一个,

但是在后一种情况下,最好在两个列上创建一个复合索引,它可以服务于两个子句。

This will use the index you need (in case it's usable):

SELECT  *
FROM    table FORCE INDEX (myindex)

MySQL collects and uses table statistics to estimate the cardinality of the indexes.

It keeps it in information_schema.statistics.

Of two indexes that may be applied for filtering, MySQL chooses the one with greater cardinality.

If there are two indexes with big cardinality, it can choose INDEX MERGE over both of them.

In one index can serve WHERE condition and another one can serve ORDER BY, MySQL seems to prefer the first one

In the latter case, however, it's better to create a composite index over both columns, which can serve both clauses.

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