MySQL IS NULL Optimization

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 IS NULL optimization example

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)
MYSQL IS NULL optimization example ref_or_null

在此示例中,应用优化时EXPLAIN显示ref_or_null

如果你有一个由两列或更多列组成的键,MySQL可以对任何键部分进行优化。

假设表t1的列c1c2上有索引,以下查询可以利用该索引:

SELECT * 
FROM t1
WHERE c1 IS NULL;
Code language: SQL (Structured Query Language) (sql)
本教程有帮助吗?