gpt4 book ai didi

MySQL:为什么这个 SQL 查询不使用索引?

转载 作者:行者123 更新时间:2023-11-29 23:18:43 25 4
gpt4 key购买 nike

我有一个非常简单的 SELECT,它采用文件排序并且不使用索引。

考虑以下查询:

SELECT * FROM forum_topic
WHERE topic_status = 0
ORDER BY modified_date LIMIT 0, 30

下表(删除了几列以使其更加简短)

CREATE TABLE `forum_topic` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`slug` varchar(255) NOT NULL,
`forum_id` int(10) NOT NULL DEFAULT '1',
`title` varchar(100) NOT NULL,
`topic_status` tinyint(1) NOT NULL DEFAULT '0',
`post_count` bigint(20) NOT NULL DEFAULT '0',
`modified_date` datetime NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `slug` (`slug`),
FULLTEXT KEY `title` (`title`),
KEY `modified` (`modified_date`, `topic_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

EXPLAIN 给出以下输出

id  select_type table?      partitions? type?   possible_keys?  key?    key_len?    ref?    rows?   Extra?
1 SIMPLE forum_topic NULL ALL NULL NULL NULL NULL 2075 Using where; Using filesort

请注意解释如何说明 possible_keys 为 NULL,以及在扫描所有行后如何使用文件排序。

请指教。谢谢。

最佳答案

此查询需要 topic_status 出现在索引的最重要位置,因为它正在搜索常量。

你有

   KEY `modified` (`modified_date`, `topic_status`)

你可能想要

   KEY `mod2` (`topic_status`, `modified_date` )

相反。这可能满足过滤器和查询的 ORDER BY ... LIMIT 部分。

专业提示:避免 SELECT * 并枚举您实际需要的列。

专业提示:文件排序并不一定是您所认为的那样。只要 MySQL 需要为排序等构建中间结果集,就会使用它。

关于MySQL:为什么这个 SQL 查询不使用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com