在oracle我们知道唯一索引是不记录null值的。
在mysql中却不一样,mysql的唯一索引是记录null值的。以下摘录5.6手册中的话
A UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE
index permits multipleNULL
values for columns that can contain NULL
. If you specify a prefix value for a column in a UNIQUE
index, the column values must be unique within the prefix.
大意是说mysql的unique索引可包含多个null值。
那在谓词条件中使用is not null时,优化器是否会选择走索引呢。
我们来验证一下:
create table test1(id int primary key,tt int unique) engine innodb;
创建一个表id为主键,tt为唯一
使用一个procedure声称数据
CREATE DEFINER=`root`@`localhost` PROCEDURE `impdata`()
BEGIN
declare i int default 0;
while i<10000 DO
set i=i+1;
if i%500=1 then
insert into test1(id,tt) values(i,null);
else
insert into test1(id,tt) values(i,i);
end if;
end while;
END
然后执行
call impdata();
创建索引
create unique index test1_unq_tt on test1(tt);
查看执行计划
mysql> explain select tt from test1 where tt is not null;
+----+-------------+-------+-------+-----------------+------+---------+------+--
----+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | r
ows | Extra |
+----+-------------+-------+-------+-----------------+------+---------+------+--
----+--------------------------+
| 1 | SIMPLE | test1 | range | tt,TEST1_UNQ_TT | tt | 5 | NULL | 9
979 | Using where; Using index |
+----+-------------+-------+-------+-----------------+------+---------+------+--
----+--------------------------+
1 row in set (0.00 sec)
可见mysql的unique的索引是包含并记录null值的