一个小坑,如题。

新建了一张表,假设如下

create table table_c
(
id int auto_increment
primary key,
req_id int null,
req_type int default 0 null,
req_version int default 0 null,
constraint table_c_req_id_req_type_uindex
unique (req_id, req_type)
)
charset = latin1;

表中有个(req_id, req_type)组成的唯一索引,插入数据一些数据后得到如下结果

从上表中插入的结果来看,可以看到有两条(req_id = 124, req_type = null)组成的行数据,可见,unique索引中可以包含null值字段

A UNIQUE index permits multiple NULL values for columns that can contain NULL.

https://dev.mysql.com/doc/refman/5.6/en/create-index.html

官方文档中提到了这么一段,确实可以包含的,且根据上面的实验结果,但凡某个字段为null了,那么唯一性约束就失效了。

相关处理办法

  1. 给unique索引相关字段添加上 not null属性 和 default
  2. 程序代码中相关对象拼装的时候校验相关字段,并赋予默认值

首先,在设置了default值之后,如果插入执行insert语句的时候没有对应字段,mysql会赋予默认的default值。其次,某些封装的JDBC操作的工具如果我们传入的字段没有值,那么工具会自动给这个字段赋值null,那么就导致如果没有设置 not null属性会被插入一个null值,仍然导致唯一索引约束失效。