【问题标题】:MySQL - RANGE CONDITION and ORDER BYMySQL - 范围条件和排序依据
【发布时间】:2015-04-29 04:48:20
【问题描述】:

在《高性能 MySQL》一书中说,

ORDER BY 子句也有与查找查询相同的限制:它需要形成索引的最左前缀。在所有其他情况下,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 使用 rent_date 索引来排序以下查询,因为您 从 EXPLAIN 中缺少文件排序可以看出:

> 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 BY 子句本身不是最左边的 索引的前缀,因为我们为 索引中的第一列。

这个查询在第一列有范围条件,所以 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不使用索引?

将使用 B-tree 索引找到匹配“rental_date”>“2005-05-25”的第一个位置。然后MySQL可以按顺序扫描子节点(inventory_id,customer_id),我想。有什么问题?

【问题讨论】:

    标签: mysql indexing sql-order-by


    【解决方案1】:

    假设索引是这样的:

    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_idcustomer_id)按排序顺序排列。

    但在第二个查询中,想象一下2005-05-262005-05-27 会发生什么。突然,inventory_idcustomer_id 没有排序。它们仅针对特定的 rental_date 值进行排序。所以mysql最终不得不对它们进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2011-07-04
      • 1970-01-01
      • 2019-07-03
      • 2021-01-14
      相关资源
      最近更新 更多