8.3.13 Descending Indexes降序索引

MySQL supports descending indexes: DESC in an index definition is no longer ignored but causes storage of key values in descending order. MySQL支持降序索引:索引定义中的DESC不再被忽略,而是导致按降序存储键值。Previously, indexes could be scanned in reverse order but at a performance penalty. 以前,可以按相反的顺序扫描索引,但会降低性能。A descending index can be scanned in forward order, which is more efficient. 降序索引可以按正向顺序扫描,这样更有效。Descending indexes also make it possible for the optimizer to use multiple-column indexes when the most efficient scan order mixes ascending order for some columns and descending order for others.当最有效的扫描顺序混合了某些列的升序和其他列的降序时,降序索引还使优化器可以使用多个列索引。

Consider the following table definition, which contains two columns and four two-column index definitions for the various combinations of ascending and descending indexes on the columns:考虑下面的表定义,它包含两列和42列索引定义,用于列上的升序和降序索引的各种组合:

CREATE TABLE t (
  c1 INT, c2 INT,
  INDEX idx1 (c1 ASC, c2 ASC),
  INDEX idx2 (c1 ASC, c2 DESC),
  INDEX idx3 (c1 DESC, c2 ASC),
  INDEX idx4 (c1 DESC, c2 DESC)
);

The table definition results in four distinct indexes. 表定义产生四个不同的索引。The optimizer can perform a forward index scan for each of the ORDER BY clauses and need not use a filesort operation:优化器可以对每个ORDER BY子句执行正向索引扫描,无需使用filesort操作:

ORDER BY c1 ASC, c2 ASC    -- optimizer can use idx1
ORDER BY c1 DESC, c2 DESC  -- optimizer can use idx4
ORDER BY c1 ASC, c2 DESC   -- optimizer can use idx2
ORDER BY c1 DESC, c2 ASC   -- optimizer can use idx3

Use of descending indexes is subject to these conditions:降序索引的使用取决于以下条件:

You can see in the Extra column of the output of EXPLAIN that the optimizer is able to use a descending index, as shown here:您可以在EXPLAIN输出的Extra列中看到优化器能够使用降序索引,如下所示:

mysql> CREATE TABLE t1 (
    -> a INT, 
    -> b INT, 
    -> INDEX a_desc_b_asc (a DESC, b ASC)
    -> );

mysql> EXPLAIN SELECT * FROM t1 ORDER BY a ASC\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: index
possible_keys: NULL
          key: a_desc_b_asc
      key_len: 10
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Backward index scan; Using index

In EXPLAIN FORMAT=TREE output, use of a descending index is indicated by the addition of (reverse) following the name of the index, like this:EXPLAIN FORMAT=TREE输出中,在索引名称后添加(reverse)表示使用降序索引,如下所示:

mysql> EXPLAIN FORMAT=TREE SELECT * FROM t1 ORDER BY a ASC\G 
*************************** 1. row ***************************
EXPLAIN: -> Index scan on t1 using a_desc_b_asc (reverse)  (cost=0.35 rows=1)

See also EXPLAIN Extra Information.另请参议题EXPLAIN额外信息