我相当确定这个问题的答案在于有一个不同的索引。我有一个不合理的慢查询,但只有当它是在以下完整的形式,如果我删除了查询的一部分,它是惊人的速度,我如何才能使它更好?
慢速:
SELECT json
FROM requests
WHERE spider = 'foo'
AND load_count = ( SELECT MIN( load_count ) FROM requests )
AND load_count < 50
LIMIT 500;解释:
+----+-------------+----------+------+-------------------------+--------------+---------+-------+--------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+-------------------------+--------------+---------+-------+--------+------------------------------+
| 1 | PRIMARY | requests | ref | load_count,spider_index | spider_index | 90 | const | 200845 | Using where |
| 2 | SUBQUERY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away |
+----+-------------+----------+------+-------------------------+--------------+---------+-------+--------+------------------------------+数据库结构:
CREATE TABLE `requests` (
`added` int(11) NOT NULL AUTO_INCREMENT,
`url` char(255) NOT NULL,
`spider` char(30) NOT NULL,
`referer` char(255) DEFAULT NULL,
`json` text NOT NULL,
`load_count` int(11) NOT NULL DEFAULT '0',
`processed` tinyint(1) NOT NULL DEFAULT '0',
`invalid` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`added`),
UNIQUE KEY `url` (`url`),
KEY `load_count` (`load_count`),
KEY `spider_index` (`spider`)
) ENGINE=MyISAM AUTO_INCREMENT=5285840 DEFAULT CHARSET=utf8在像Neo建议的那样更新我的索引后,我得到了巨大的改进:
+----+-------------+----------+------+-------------------+-------------------+---------+-------------+------+------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+------+-------------------+-------------------+---------+-------------+------+------------------------------+
| 1 | PRIMARY | requests | ref | spider_load_count | spider_load_count | 94 | const,const | 1487 | Using where |
| 2 | SUBQUERY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Select tables optimized away |
+----+-------------+----------+------+-------------------+-------------------+---------+-------------+------+------------------------------+发布于 2011-04-07 17:04:03
alter table requests drop index load_count;
alter table requests drop index spider_index;
alter table requests add index spider_load_count(load_count, spider);发布于 2011-04-07 16:53:19
那这个呢?
SELECT MIN(load_count) INTO @min_load_count FROM requests;
SELECT json
FROM requests
WHERE load_count = @min_load_count
AND load_count < 50
LIMIT 500;在爬行器字段上建立索引可能会对您有所帮助。
发布于 2011-04-07 16:58:50
以下是一些意见/建议:
和load_count,但是没有覆盖这两个字段的索引。添加一个同时包含两个值的索引可能会修复这个示例。和前两个查询在WHERE中有“ load_count < 50”,这是不需要的,因为您还有一个"load_count = exact value“。MySQL将在其查询优化中忽略"AND load_count < 50“。
https://stackoverflow.com/questions/5578308
复制相似问题