3

I am wondering why my query isn't using the index "created_2" which covers all the fields used in the query. It seems to use a filesort. What are the rules for picking an index?

Query:

SELECT * FROM (`stories`) WHERE `image_full_url` != '' AND `order` != 0 ORDER BY `created` DESC, `order` DESC LIMIT 5

Create Table:

| stories | CREATE TABLE `stories` (
  `id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `news_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `author` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `author_title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `image_caption` text COLLATE utf8_unicode_ci,
  `image_credit` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `image_full_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `body` text COLLATE utf8_unicode_ci,
  `summary` text COLLATE utf8_unicode_ci,
  `external_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `order` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `news_type` (`news_type`),
  KEY `created` (`created`),
  KEY `news_type_2` (`news_type`,`created`),
  KEY `created_2` (`created`,`image_full_url`,`order`),
  KEY `image_full_url` (`image_full_url`,`order`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

Explain:

mysql> explain SELECT * FROM (`stories`) WHERE `image_full_url` != '' AND `order` != 0 ORDER BY `created` DESC, `order` DESC LIMIT 5;
+----+-------------+---------+-------+----------------+----------------+---------+------+------+-----------------------------+
| id | select_type | table   | type  | possible_keys  | key            | key_len | ref  | rows | Extra                       |
+----+-------------+---------+-------+----------------+----------------+---------+------+------+-----------------------------+
|  1 | SIMPLE      | stories | range | image_full_url | image_full_url | 768     | NULL |   25 | Using where; Using filesort |
+----+-------------+---------+-------+----------------+----------------+---------+------+------+-----------------------------+
1 row in set (0.00 sec)
4

1 に答える 1

3

ルールの完全なセットはここorder byにあり、インデックスの連続していない部分を参照する場合、インデックスを使用できないと述べています。インデックスを ( created, image_full_url, order) から ( created, order, ) に変更するimage_full_urlと、おそらく使用できるようになります。

于 2012-11-14T13:52:55.220 に答える