1

Does InnoDB support a "UNIQUE IF NOT NULL" index? I.e. a UNIQUE index which allows multiple NULL values?

(I guess no since I wasn't able to find anything about that — found a lot of kinda-related things but not a definitive answer)

4

1 回答 1

2

In InnoDB unique secondary indexes support multiple NULLs (primary indexes don't support NULL at all). For example:

mysql> create table x (i int, j int, primary key (i), unique key (j));
mysql> insert into x (i,j) values (NULL,NULL);
ERROR 1048 (23000): Column 'i' cannot be null
mysql> insert into x (i,j) values (1,NULL);
mysql> insert into x (i,j) values (2,NULL);
mysql> insert into x (i,j) values (3,3);
mysql> select * from x;
+---+------+
| i | j    |
+---+------+
| 1 | NULL |
| 2 | NULL |
| 3 |    3 |
+---+------+
3 rows in set (0.01 sec)

mysql> insert into x (i,j) values (4,3);
ERROR 1062 (23000): Duplicate entry '3' for key 'j'
于 2013-04-04T21:34:05.390 回答