为什么使用WHERE IN子句进行更长时间的查询比短进行查询更快?

时间:2016-10-13 17:48:04

标签: mysql where-in

我试图弄清楚为什么较长的查询比短的查询运行得更快。可能是由于某些索引?

此查询大约需要半秒钟。

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中完成。

以下是返回的解释:

更快,更长的查询:

enter image description here

更慢,更短的查询:

enter image description here

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

这些是该表的索引:

enter image description here

0 个答案:

没有答案