我有一个简单的表结构,从以下查询中可以看出:
SELECT j.*
FROM jobs j
WHERE j.reserved_until < 1520028463911
AND j.scheduled_time < 1520024838836
AND j.retries < 5
AND j.active = 1
LIMIT 1000
我使用此查询作为更新的一部分,以排除竞争条件的可能性并保留一些工作
UPDATE jobs AS j
INNER JOIN
(
SELECT j.job_id
FROM jobs j
WHERE j.active = 1
AND j.scheduled_time < :now
AND reserved_until < :now
AND j.retries < :max_retries
ORDER BY j.scheduled_time
LIMIT :count
) S ON j.job_id = S.job_id
SET
j.reserved_by = :reserved_by,
j.reserved_until = :reserved_until
但是当我对上面描述的选择进行解释时,它给了我这个查询非常高的成本。我所做的是我尝试创建一个可以降低查询成本的索引。我尝试过不同的索引组合,并为字段(reserved_until, scheduled_time, retries, active)
创建了一个复合索引,但它没有任何改进。我做错了什么,根据我的理解,这个选择应该从我提供的索引中选择1000?
提前谢谢!
修改的
以下是解释结果:
id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'SIMPLE', 'j', NULL, 'range', 'jobs_retries,jobs_scheduled_time,jobs_reserved_until', 'jobs_retries', '4', NULL, '254466', '2.50', 'Using index condition; Using where'
修改的
CREATE TABLE `jobs` (
`job_id` bigint(20) NOT NULL AUTO_INCREMENT,
`url` varchar(256) NOT NULL,
`type` int(11) NOT NULL,
`active` tinyint(1) NOT NULL,
`scheduled_time` double NOT NULL,
`reserved_by` int(11) NOT NULL,
`reserved_until` double NOT NULL,
`external_id` bigint(20) NOT NULL,
`retries` int(11) NOT NULL,
PRIMARY KEY (`job_id`),
KEY `type` (`type`),
KEY `jobs_url` (`url`),
KEY `jobs_reserved_by` (`reserved_by`),
KEY `jobs_external_id` (`external_id`),
KEY `jobs_retries` (`retries`),
KEY `jobs_scheduled_time` (`scheduled_time`),
KEY `jobs_reserved_until` (`reserved_until`),
CONSTRAINT `jobs_ibfk_1` FOREIGN KEY (`type`) REFERENCES `job_types` (`job_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=509135 DEFAULT CHARSET=utf8
其他编辑
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE j NULL range jobs_retries,jobs_scheduled_time,jobs_reserved_until,jobs_another_index jobs_retries 4 NULL 252116 2.5 Using index condition; Using where
其他编辑
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE j NULL range jobs_retries,jobs_scheduled_time,jobs_reserved_until,jobs_another_index jobs_retries 4 NULL 252116 2.5 Using index condition; Using where