8.3.11 Optimizer Use of Generated Column Indexes优化器使用生成的列索引

MySQL supports indexes on generated columns. MySQL支持生成列的索引。For example:例如:

CREATE TABLE t1 (f1 INT, gc INT AS (f1 + 1) STORED, INDEX (gc));

The generated column, gc, is defined as the expression f1 + 1. 生成的列gc被定义为表达式f1+1The column is also indexed and the optimizer can take that index into account during execution plan construction. 列也被索引,优化器可以在执行计划构建期间考虑该索引。In the following query, the WHERE clause refers to gc and the optimizer considers whether the index on that column yields a more efficient plan:在以下查询中,WHERE子句引用gc,优化器考虑该列上的索引是否生成更高效的计划:

SELECT * FROM t1 WHERE gc > 9;

The optimizer can use indexes on generated columns to generate execution plans, even in the absence of direct references in queries to those columns by name. 优化器可以在生成的列上使用索引来生成执行计划,即使在按名称查询这些列时没有直接引用。This occurs if the WHERE, ORDER BY, or GROUP BY clause refers to an expression that matches the definition of some indexed generated column. 如果WHEREORDER BYGROUP BY子句引用的表达式与某个索引生成列的定义相匹配,则会发生这种情况。The following query does not refer directly to gc but does use an expression that matches the definition of gc:以下查询不直接引用gc,而是使用与gc定义匹配的表达式:

SELECT * FROM t1 WHERE f1 + 1 > 9;

The optimizer recognizes that the expression f1 + 1 matches the definition of gc and that gc is indexed, so it considers that index during execution plan construction. 优化器识别出表达式f1 + 1gc的定义相匹配,并且gc被索引,因此它在执行计划构建期间考虑该索引。You can see this using EXPLAIN:您可以使用EXPLAIN来查看这一点:

mysql> EXPLAIN SELECT * FROM t1 WHERE f1 + 1 > 9\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: range
possible_keys: gc
          key: gc
      key_len: 5
          ref: NULL
         rows: 1
     filtered: 100.00
        Extra: Using index condition

In effect, the optimizer has replaced the expression f1 + 1 with the name of the generated column that matches the expression. 实际上,优化器已将表达式f1 + 1替换为与表达式匹配的生成列的名称。That is also apparent in the rewritten query available in the extended EXPLAIN information displayed by SHOW WARNINGS:这一点在SHOW WARNINGS显示的扩展EXPLAIN信息中的重写查询中也很明显:

mysql> SHOW WARNINGS\G
*************************** 1. row ***************************
  Level: Note
   Code: 1003
Message: /* select#1 */ select `test`.`t1`.`f1` AS `f1`,`test`.`t1`.`gc`
         AS `gc` from `test`.`t1` where (`test`.`t1`.`gc` > 9)

The following restrictions and conditions apply to the optimizer's use of generated column indexes:以下限制和条件适用于优化器使用生成的列索引: