让 SQL 使用正确的索引
我有一个包含两个索引的表,其中一个是特定查询的更快覆盖索引。 然而,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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将使用您需要的索引(如果它可用):
MySQL 收集并使用表统计信息来估计索引的基数。
它将其保存在
information_schema.statistics
中。在可用于过滤的两个索引中,
MySQL
选择基数较大的一个。如果有两个基数较大的索引,则可以对这两个索引选择
INDEX MERGE
。在一个索引可以提供
WHERE
条件,另一个索引可以提供ORDER BY
条件时,MySQL
似乎更喜欢第一个,但是在后一种情况下,最好在两个列上创建一个复合索引,它可以服务于两个子句。
This will use the index you need (in case it's usable):
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 serveORDER BY
,MySQL
seems to prefer the first oneIn the latter case, however, it's better to create a composite index over both columns, which can serve both clauses.