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 @   bf378  阅读(449)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2020-01-13 Excel高效处理数据-按照列进行数据求和
2020-01-13 Excel高效处理数据-按照行进行数据求和
点击右上角即可分享
微信分享提示