MySQL:唯一索引中的NULL值

郎家岭伯爵 2023年03月15日 391次浏览

前言

MySQL 中的 UNIQUE 索引,可以在一个或多个列中强制实现值的唯一性。但唯一索引中存在一个特性——那就是 NULL 值在 MySQL 中被视为不同的值

因此如果在 UNIQUE 索引中出现 NULL 值,那么其唯一性就失效了。

实现

单列UNIQUE索引

建表语句:

create table unique_test(
id bigint(16) not null comment '用户id',
name varchar(50) default null comment '用户名字',
uniqueId varchar(50) default null comment '唯一索引测试字段',
unique key(uniqueId)
)engine=innodb default charset=utf8mb4 comment '测试单列唯一索引'

数据入库测试:

多列UNIQUE索引

建表语句:

create table unique_test(
id bigint(16) not null comment '用户id',
name varchar(50) default null comment '用户名字',
uniqueId varchar(50) default null comment '唯一索引测试字段',
unique key(name, uniqueId)
)engine=innodb default charset=utf8mb4 comment '测试多列唯一索引'

数据入库测试:

总结

其他数据库系统不同,MySQL 将 NULL 值视为不同的值。 因此,我们可以在 UNIQUE 索引中具有多个 NULL 值。

赞助页面示例