gpt4 book ai didi

mysql查询扫描所有行

转载 作者:行者123 更新时间:2023-11-29 06:04:01 24 4
gpt4 key购买 nike

伙计们试图让我了解 mysql 查询为什么它扫描表中的所有行

我有 2 个表 topic_entry 和 topic_user

CREATE TABLE `topic_entry` (
`entry_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`topic_id` bigint(20) unsigned NOT NULL,
`entry_created` datetime NOT NULL,
`entry_object` text,
`level` tinyint(4) NOT NULL DEFAULT '3',
PRIMARY KEY (`entry_id`),
KEY `entry_created` (`entry_created`),
KEY `level` (`level`),
KEY `topic_id_2` (`topic_id`,`entry_id`)
) ENGINE=MyISAM;

CREATE TABLE `topic_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`topic_id` bigint(20) unsigned NOT NULL,
`user_id` varchar(100) NOT NULL,
`private` enum('y','n') DEFAULT NULL,
`freq` enum('a','d','w') DEFAULT NULL,
`topic_id_freq` varchar(10) DEFAULT NULL,
`casematch` enum('0','1') DEFAULT '0',
`textmatch` enum('0','1') DEFAULT '0',
`topic_name_case` varchar(100) DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `topic_id_user_id` (`topic_id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `topic_id_freq` (`topic_id_freq`)
) ENGINE=MyISAM;

这是我尝试运行的查询

explain 
select te.topic_id,te.entry_id
from topic_entry te
WHERE te.topic_id in (select topic_id
from topic_user where user_id ='xyz')
AND te.level=4
AND te.entry_id > 0
ORDER BY te.entry_id DESC
LIMIT 5;

解释输出显示它正在扫描所有行

|  1 | PRIMARY| te | range  | PRIMARY,level | PRIMARY | 8 | NULL| **722978** | Using where              | 
| 2 | DEPENDENT SUBQUERY | topic_user | unique_subquery | topic_id_user_id,user_id | topic_id_user_id | 310 | func,const | 1 | Using index; Using where |

最佳答案

试试这个:

EXPLAIN
SELECT te.topic_id,te.entry_id
FROM topic_entry te
JOIN topic_user tu ON te.topic_id = tu.topic_id AND tu.user_id = 'xyz'
WHERE te.level=4
AND te.entry_id > 0
ORDER BY te.entry_id DESC
LIMIT 5;

关于mysql查询扫描所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392213/

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