在“高性能MySQL”一书中,
ORDER子句还具有与查找查询相同的限制:它需要形成索引的最左边前缀。在所有其他情况下,MySQL使用一个文件短。
下面是一个有索引的表(rental_date,inventory_id,customer_id):
CREATE TABLE rental (
...
PRIMARY KEY (rental_id),
UNIQUE KEY rental_date (rental_date,inventory_id,customer_id),
KEY idx_fk_inventory_id (inventory_id),
KEY idx_fk_customer_id (customer_id),
KEY idx_fk_staff_id (staff_id),
...
);MySQL使用rental_date索引对以下查询进行排序,从解释中缺少一个文件可以看出:
> mysql> EXPLAIN SELECT
> rental_id, staff_id FROM sakila.rental
> -> WHERE rental_date = '2005-05-25'
> -> ORDER BY inventory_id, customer_id\G
> *************************** 1. row ***************************
> type: ref
> possible_keys: rental_date
> key: rental_date
> rows: 1
> Extra: Using where 尽管ORDER子句本身并不是索引的最左前缀,但这是可行的,因为我们为索引中的第一列指定了一个相等的条件。
和
此查询对第一列具有范围条件,因此MySQL不使用其余的索引:
EXPLAIN
SELECT `rental_id`, `staff_id` FROM `sakila`.`rental`
WHERE `rental_date` > '2005-05-25'
ORDER BY `inventory_id`, `customer_id`;
*************************** 1. row ***************************
...
key: NULL Extra: Using where; using filesort
...问题:为什么查询在第一列上有范围条件,MySQL不使用索引?
与'rental_date‘> '2005-05-25’>匹配的第一个位置将使用B树索引找到.我认为MySQL可以按顺序扫描子节点(inventory_id,customer_id)。有什么问题吗?
发布于 2015-02-26 17:30:49
假设索引是这样的:
rental_date, inventory_id, customer_id
======================================
...
2005-05-25, 10, 10
2005-05-25, 20, 20
2005-05-25, 30, 30
2005-05-26, 20, 20
2005-05-26, 40, 40
2005-05-27, 10, 10
2005-05-27, 30, 30
...在第一个查询中,mysql使用索引查找第一个条目“2005-05-25”。由于rental_date是索引的第一个字段,因此相同日期值的其他字段(inventory_id、customer_id)按排序顺序排列。
但是在第二个查询中,想象一下2005-05-26,2005-05-27会发生什么。突然,inventory_id,customer_id没有排序。它们仅根据特定的rental_date值进行排序。所以mysql最终必须对它们进行排序。
https://stackoverflow.com/questions/28748724
复制相似问题