MySQL:唯一索引与NULL


#MySQL 笔记


null破坏了唯一性。我们用示例看下如何破坏的。

单列唯一

创建表,c1列加上唯一索引:

create table test_table (
    c1 CHAR(2),
    UNIQUE KEY uk_c1(c1)
) engine = InnoDB character set = utf8mb4;

虽然 c1 列被设置为保证唯一性,但对 NULL 是无效的,即可以插入多条 NULL 数据。我们看下效果:

步骤 执行的SQL 结果
1 insert into test_table(c1) values('你好'); 成功
2 insert into test_table(c1) values('你好'); 失败,报错 (1062, u"Duplicate entry '\u4f60\u597d' for key 'uk_c1'")
3 insert into test_table(c1) values(NULL); 成功
4 insert into test_table(c1) values(NULL); 成功

查看下表中数据:

mysql> select * from test_table;
+--------+
| c1     |
+--------+
| <null> |
| <null> |
| 你好   |
+--------+

多列唯一

创建表,c1和c2列加上联合的唯一索引。

create table test_table (
    c1 CHAR(2),
    c2 CHAR(2),
    UNIQUE KEY uk_c1_c2(c1, c2)
) engine = InnoDB character set = utf8mb4;

当有数据为null时,唯一性无法满足。

步骤 执行的SQL 结果
1 insert into test_table(c1, c2) values('你好', '世界'); 成功
2 insert into test_table(c1, c2) values('你好', '世界'); 执行失败,报错 (1062, u"Duplicate entry '\u4f60\u597d-\u4e16\u754c' for key 'uk_c1_c2'")
3 insert into test_table(c1, c2) values('你好', null); 成功
4 insert into test_table(c1, c2) values('你好', null); 成功
5 insert into test_table(c1, c2) values(null, null); 成功
6 insert into test_table(c1, c2) values(null, null); 成功

查看表中数据:

mysql> select * from test_table;
+--------+--------+
| c1     | c2     |
+--------+--------+
| <null> | <null> |
| <null> | <null> |
| 你好   | <null> |
| 你好   | <null> |
| 你好   | 世界   |
+--------+--------+

null破坏了唯一性,怎么办?

当唯一列出现null时,唯一性得不到满足,怎么办?

  1. 不允许列出现 null 值,即not null
  2. 给列增加 default 值,注意default值不能是 null。


( 本文完 )