我试图弄清楚为什么较长的查询比短的查询运行得更快。可能是由于某些索引?
此查询大约需要半秒钟。
SELECT *
FROM (SELECT `positions`.`id`,
`positions`.`keyword_id`,
`positions`.`position`,
@rank := IF(@group = keyword_id, @rank + 1, 1) AS
rank_08b5648409889380fe88d86c30ff4c8d,
@group := keyword_id AS
group_08b5648409889380fe88d86c30ff4c8d
FROM (SELECT @rank := 0,
@group := 0) AS vars,
positions
ORDER BY `keyword_id` ASC,
`created_at` DESC) AS positionsA
LEFT JOIN `positions`
ON `positionsa`.`id` = `positions`.`id`
WHERE `rank_08b5648409889380fe88d86c30ff4c8d` <= '2'
AND `positions`.`keyword_id` IN ( '1', '2', '3', ..., '1879', '1880' )
虽然这个完全相同的查询,IN
语句中的项目少了大约2秒:
SELECT *
FROM (SELECT `positions`.`id`,
`positions`.`keyword_id`,
`positions`.`position`,
@rank := IF(@group = keyword_id, @rank + 1, 1) AS
rank_08b5648409889380fe88d86c30ff4c8d,
@group := keyword_id AS
group_08b5648409889380fe88d86c30ff4c8d
FROM (SELECT @rank := 0,
@group := 0) AS vars,
positions
ORDER BY `keyword_id` ASC,
`created_at` DESC) AS positionsA
LEFT JOIN `positions`
ON `positionsa`.`id` = `positions`.`id`
WHERE `rank_08b5648409889380fe88d86c30ff4c8d` <= '2'
AND `positions`.`keyword_id` IN ( '1', '2', '3', ..., '164', '165' )
所有性能测试均在PHPmyAdmin中完成。
以下是返回的解释:
更快,更长的查询:
更慢,更短的查询:
show create table positions
会返回此信息:
CREATE TABLE `positions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`keyword_id` int(11) NOT NULL,
`position` int(11) NOT NULL,
`url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `keyword_id_created_at_index` (`keyword_id`,`created_at`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=467923 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
这些是该表的索引: