8.2.1.14 Constant-Folding Optimization常数折叠优化

Comparisons between constants and column values in which the constant value is out of range or of the wrong type with respect to the column type are now handled once during query optimization rather row-by-row than during execution. 如果常量值超出范围或列类型错误,则常量和列值之间的比较现在在查询优化期间处理一次,而不是在执行期间逐行处理。The comparisons that can be treated in this manner are >, >=, <, <=, <>/!=, =, and <=>.可以以这种方式处理的比较包括>>=<<=<>/!==<=>

Consider the table created by the following statement:考虑以下语句创建的表:

CREATE TABLE t (c TINYINT UNSIGNED NOT NULL);

The WHERE condition in the query SELECT * FROM t WHERE c < 256 contains the integral constant 256 which is out of range for a TINYINT UNSIGNED column. 查询SELECT * FROM t WHERE c < 256中的WHERE条件包含整数常量256,该常量超出了TINYINT UNSIGNED列的范围。Previously, this was handled by treating both operands as the larger type, but now, since any allowed value for c is less than the constant, the WHERE expression can instead be folded as WHERE 1, so that the query is rewritten as SELECT * FROM t WHERE 1.以前,这是通过将两个操作数都视为较大的类型来处理的,但现在,由于c的任何允许值都小于常量,因此WHERE表达式可以折叠为WHERE 1,以便将查询重写为SELECT * FROM t WHERE 1

This makes it possible for the optimizer to remove the WHERE expression altogether. 这使得优化器可以完全删除WHERE表达式。If the column c were nullable (that is, defined only as TINYINT UNSIGNED) the query would be rewritten like this:如果列c可为空(即,仅定义为TINYINT UNSIGNED),则查询将被重写如下:

SELECT * FROM t WHERE ti IS NOT NULL

Folding is performed for constants compared to supported MySQL column types as follows:与支持的MySQL列类型相比,对常量执行折叠,如下所示:

Limitations.局限性  This optimization cannot be used in the following cases:此优化不能用于以下情况:

  1. With comparisons using BETWEEN or IN.使用BETWEENIN比较。

  2. With BIT columns or columns using date or time types.具有BIT列或使用日期或时间类型的列。

  3. During the preparation phase for a prepared statement, although it can be applied during the optimization phase when the prepared statement is actually executed. 在准备语句的准备阶段,尽管它可以在实际执行准备语句的优化阶段应用。This due to the fact that, during statement preparation, the value of the constant is not yet known.这是因为在语句准备期间,常数的值还未知。