MYSQL的UNIQUE索引包含null值及验证

在oracle我们知道唯一索引是不记录null值的。

在mysql中却不一样,mysql的唯一索引是记录null值的。以下摘录5.6手册中的话

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值的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值