在MySQL中的唯一索引(约束)
创建方法一 在创表的语句中顺便创建唯一索引
CREATE TABLE some_table (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(32) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX (name)
);
创建方法二 使用创建索引的语句
CREATE UNIQUE INDEX name (name) ON some_table;
关于创建了 UNIQUE INDEX 的字段上的 NULL 问题
要点一:
与PRIMARY KEY 不同的是,UNIQUE INDEX可以在 NULLable 字段上创建,并且不会将该字段转换成 NOT NULL;
要点二:
除了少数存储引擎(BDB),其他的存储引擎都允许 multiple NULL values,即可存在多条该字段值为 NULL 的行。
下面的MySQL官网文档的说明。
A UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL
values except for the BDB
storage engine. For other engines, a UNIQUE
index permits multiple NULL
values for columns that can contain NULL
. If you specify a prefix value for a column in a UNIQUE
index, the column values must be unique within the prefix.