MySQL索引不用于简单的选择查询

时间:2013-12-01 09:44:47

标签: mysql

我有一张桌子

CREATE TABLE `pd` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `language_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `meta_description` varchar(255) NOT NULL,
  `meta_keyword` varchar(255) NOT NULL,
  `seo_title` varchar(255) NOT NULL,
  `seo_h1` varchar(255) NOT NULL,
  PRIMARY KEY (`product_id`,`language_id`),
  KEY `language_id` (`description`(128),`language_id`),
  KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=47019 DEFAULT CHARSET=utf8;

当我运行此查询时

EXPLAIN SELECT * FROM `pd` ORDER BY product_id;

我得到了这个结果:

+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows   | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+
|  1 | SIMPLE      | pd    | index | NULL          | PRIMARY | 8       | NULL | 139551 |       |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------+

当我运行此查询时

EXPLAIN SELECT * FROM `pd` ORDER BY name;

我得到了这个结果:

+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra          |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+
|  1 | SIMPLE      | pd    | ALL  | NULL          | NULL | NULL    | NULL | 137762 | Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------+

为什么不使用第二种情况索引?我看到的唯一区别是product_id是主键的一部分,而name是非唯一索引。

1 个答案:

答案 0 :(得分:1)

只要name不是群集密钥 - 首先读取索引并在数据中逐个查找每一行将会更加昂贵。

所以mysql(我认为其他任何人都会DBMS)决定读取数据并在内存中对其进行排序。