MYSQL的UNIQUE索引包含null值及驗證
在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 multiple
NULL
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值的