mysql - Order by 没有使用索引,奇怪的行为?

标签 mysql

当我尝试使用 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/

相关文章:

mysql - 从 mysql 表结果中删除重复行

mysql - 将此 MySQL 转换为 Sybase

java - 创建一个使用 mysql 数据库的 java 应用程序后,用户的计算机需要什么才能正常运行?

php - 在 Phalcon 中执行查询时出错,但查询在 phpMyAdmin 上有效

PHP:基于 2 列将 mysql 数据库导出为 CSV?

mysql - 列出收入高于经理的员工姓名

php - 使用 DB::raw 表达式的 POINT/POLYGON 等 Laravel 模型

mysql - 从批处理脚本中转义 MYSQL 插入

java - 登录-注销 session 无法正常工作

php - MYSQL + PHP 将两行数据显示为单列