当我尝试使用 where 和 order 获取一些 mysql 数据时遇到一些问题。
即使我使用 where 或简单地排序,订单也没有使用表索引。
我有这张 table
CREATE TABLE IF NOT EXISTS `myTable`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` mediumint(9) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `title` (`title`),
KEY `price` (`price`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ;
我有这个插入的行,它们是演示行,行数可能达到 10.000
INSERT INTO `myTable` (`id`, `title`, `price`)
VALUES
(1, 'pede. Praesent eu dui. Cum', 552),
(2, 'lobortis tellus justo sit amet', 663),
(3, 'Nulla tempor augue ac ipsum.', 87),
(4, 'Ut sagittis lobortis mauris. Suspendisse', 653),
(5, 'orci luctus et ultrices posuere', 88),
(6, 'In at pede. Cras vulputate', 474),
(7, 'erat eget ipsum. Suspendisse sagittis.', 686),
(8, 'magna nec quam. Curabitur vel', 999),
(9, 'felis eget varius ultrices, mauris', 23),
(10, 'ut, pharetra sed, hendrerit a,', 943);
这是我的问题
Explain SELECT id,title,price FROM `myTable` order by price
没有使用任何索引,正在使用文件排序。
Explain SELECT price FROM `myTable` order by price
正在使用价格指数,但我需要获取所有数据,而不仅仅是价格。
最佳答案
创建覆盖索引
CREATE INDEX `idx_price_title` ON myTable(price,title);
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0
现在看explain
计划,它使用了正确的索引
Explain SELECT id,title,price FROM `myTable` order by price;
+----+-------------+---------+-------+---------------+-----------------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+-----------------+---------+------+------+-------------+
| 1 | SIMPLE | myTable | index | NULL | idx_price_title | 772 | NULL | 10 | Using index |
+----+-------------+---------+-------+---------------+-----------------+---------+------+------+-------------+
1 row in set (0.00 sec)
关于mysql - Order by 没有使用索引,奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21930717/