mysql 唯一索引对于含有null字段的唯一性约束

建表语句

create table user_info_replace
(
    id        bigint unsigned auto_increment
        primary key,
    user_name varchar(32)        not null,
    age       smallint default 0 null,
    addr      varchar(32)        null,
    constraint uniq_idx unique (user_name, age, addr)
) engine = innodb;

插入数据:

INSERT INTO user_info_replace (user_name, age, addr) VALUES ('lady', 19, null);
INSERT INTO user_info_replace (user_name, age, addr) VALUES ('lady', 19, null);
INSERT INTO user_info_replace (user_name, age, addr) VALUES ('lady', 19, null);
INSERT INTO user_info_replace (user_name, age, addr) VALUES ('lady', 19, '1');
INSERT INTO user_info_replace (user_name, age, addr) VALUES ('lady', 19, '1');

除了第五行insert之外,其余都会成功。
[2023-01-13 19:18:49] [23000][1062] Duplicate entry 'lady-19-1' for key 'user_info_replace.uniq_idx'

原因分析

null是一个空值,既然空值没有类型也没有具体的内容所以每一个null数据库都认为是不同的。所谓第一行到第三行数据 数据库不会认为冲突的。

例如: select null = null 返回值 null ;数据库对于null推荐使用is null判断,is 可以理解是=的重载运算符专门用于null的判比。

posted @ 2023-01-13 19:21  bf378  阅读(407)  评论(0编辑  收藏  举报