MySQL can perform the same optimization on MySQL可以对col_name
IS NULL
that it can use for col_name
=
constant_value
. col_name
=
constant_value
使用的col_name
为NULL
执行相同的优化。For example, MySQL can use indexes and ranges to search for 例如,MySQL可以使用索引和范围使用NULL
with IS NULL
.IS NULL
来搜索NULL
。
Examples:示例:
SELECT * FROMtbl_name
WHEREkey_col
IS NULL; SELECT * FROMtbl_name
WHEREkey_col
<=> NULL; SELECT * FROMtbl_name
WHEREkey_col
=const1
ORkey_col
=const2
ORkey_col
IS NULL;
If a 如果WHERE
clause includes a col_name
IS NULL
condition for a column that is declared as NOT NULL
, that expression is optimized away. WHERE
子句包含声明为NOT NULL
的列的col_name
IS NULL
条件,则该表达式将被优化掉。This optimization does not occur in cases when the column might produce 在列可能会生成NULL
anyway (for example, if it comes from a table on the right side of a LEFT JOIN
).NULL
的情况下(例如,如果它来自LEFT JOIN
右侧的表),则不会发生这种优化。
MySQL can also optimize the combination MySQL还可以优化
, a form that is common in resolved subqueries. col_name
= expr
OR col_name
IS NULL
的组合,这在已解析的子查询中很常见。col_name
= expr
OR col_name
IS NULLEXPLAIN
shows ref_or_null
when this optimization is used.EXPLAIN
在使用此优化时显示ref_or_null
。
This optimization can handle one 此优化可以处理任何关键部分的IS NULL
for any key part.IS NULL
。
Some examples of queries that are optimized, assuming that there is an index on columns 假设表a
and b
of table t2
:t2
的a
列和b
列上有索引,则一些优化查询示例如下:
SELECT * FROM t1 WHERE t1.a=expr
OR t1.a IS NULL;
SELECT * FROM t1, t2 WHERE t1.a=t2.a OR t2.a IS NULL;
SELECT * FROM t1, t2
WHERE (t1.a=t2.a OR t2.a IS NULL) AND t2.b=t1.b;
SELECT * FROM t1, t2
WHERE t1.a=t2.a AND (t2.b=t1.b OR t2.b IS NULL);
SELECT * FROM t1, t2
WHERE (t1.a=t2.a AND t2.a IS NULL AND ...)
OR (t1.a=t2.a AND t2.a IS NULL AND ...);
ref_or_null
works by first doing a read on the reference key, and then a separate search for rows with a NULL
key value.ref_or_null
的工作原理是首先读取引用键,然后单独搜索具有null
键值的行。
The optimization can handle only one 优化只能处理一个IS NULL
level. IS NULL
的级别。In the following query, MySQL uses key lookups only on the expression 在下面的查询中,MySQL只在表达式上使用键查找(t1.a=t2.a AND t2.a IS NULL)
and is not able to use the key part on b
:(t1.a=t2.a AND t2.a IS NULL)
,不能在b
上使用键部分:
SELECT * FROM t1, t2 WHERE (t1.a=t2.a AND t2.a IS NULL) OR (t1.b=t2.b AND t2.b IS NULL);