MySQL 对IS NULL
运算符执行优化的方式与对等于 ( =
) 运算符执行的优化相同。
例如,MySQL 在使用IS NULL
运算符搜索NULL
时使用索引,如以下查询所示:
SELECT
customerNumber,
salesRepEmployeeNumber
FROM
customers
WHERE
salesRepEmployeeNumber IS NULL;
Code language: SQL (Structured Query Language) (sql)
请参阅查询的EXPLAIN
:
EXPLAIN SELECT
customerNumber,
salesRepEmployeeNumber
FROM
customers
WHERE
salesRepEmployeeNumber IS NULL;
Code language: SQL (Structured Query Language) (sql)

MySQL 还可以针对col = value OR col IS NULL
组合进行优化,请参阅以下示例:
EXPLAIN SELECT
customerNumber,
salesRepEmployeeNumber
FROM
customers
WHERE
salesRepEmployeeNumber = 1370 OR
salesRepEmployeeNumber IS NULL;
Code language: SQL (Structured Query Language) (sql)

在此示例中,应用优化时EXPLAIN
显示ref_or_null
。
如果你有一个由两列或更多列组成的键,MySQL可以对任何键部分进行优化。
假设表t1
的列c1
和c2
上有索引,以下查询可以利用该索引:
SELECT *
FROM t1
WHERE c1 IS NULL;
Code language: SQL (Structured Query Language) (sql)
本教程有帮助吗?