我想从 entrytable
中选择 text
列的内容。
EXPLAIN SELECT text
FROM entrytable
WHERE user = 'username' &&
`status` = '1' && (
`status_spam_user` = 'no_spam'
|| (
`status_spam_user` = 'neutral' &&
`status_spam_system` = 'neutral'
)
)
ORDER BY datum DESC
LIMIT 6430 , 10
该表有三个索引:
- index_user(用户)
- index_datum(基准)
- index_status_mit_spam(状态、status_spam_user、status_spam_system)
EXPLAIN 结果是:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE entrytable ref index_user,index_status_mit_spam index_user 32 const 7800 Using where; Using filesort
possible_keys
是 MySQL 可能想要使用的索引,而keys
是 MySQL 实际使用的索引吗?- 为什么不使用索引
index_status_mit_spam
?在查询中,列的顺序与索引中的相同,... - 为什么
ORDER BY
不使用索引index_datum
? - 如何优化我的表索引或查询? (上面的查询最多需要 3 秒,表中有大约一百万个条目)
最佳答案
回答您的问题:
possible_keys
是 MySQL 可能想要使用的索引,keys
是 MySQL 实际使用的索引吗?是的,这是正确的。为什么未使用索引
index_status_mit_spam
?在查询中,列的顺序与索引中的顺序相同。 SQL 使用表索引的统计信息 来确定使用哪个索引。 select 语句中的字段顺序对使用哪个索引没有影响。索引相关的统计信息包括索引的唯一性等信息。可能会使用更多唯一索引。在这里阅读更多相关信息:http://dev.mysql.com/doc/innodb/1.1/en/innodb-other-changes-statistics-estimation.html或此处:http://dev.mysql.com/doc/refman/5.0/en//myisam-index-statistics.html .这些因素决定了 MySQL 如何选择一个索引来使用。它只会使用一个索引。为什么索引
index_datum
不用于ORDER BY
? MySQL 在查询期间只会使用一个索引而不是两个索引,因为使用第二个索引会进一步减慢查询速度。读取索引不是读取表。这关系到查询的运行效率。以下是可以解释一些概念的答案:https://dba.stackexchange.com/questions/18528/performance-difference-between-clustered-and-non-clustered-index/18531#18531或者 Adding limit clause to MySQL query slows it down dramatically或者 MySQL indexes and when to group them .这些答案有很多细节,可以帮助您了解 MySQL 索引。如何优化我的表索引或查询? (上面的查询最多需要 3 秒,表中有大约一百万个条目)。那么这里有一个文件排序可能会减慢你的速度。可能是表的索引太多,MySQL 选择了错误的索引。
您需要了解索引会加快读取速度并减慢写入表的速度。所以只添加索引并不总是一个好主意。上述答案和提示应该可以帮助您获得扎实的理解。
关于mysql - 如何解释 MySQL EXPLAIN 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14137549/