在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.
本文介绍了MySQL中唯一索引的创建方法及注意事项,包括在创建表时直接定义唯一索引和通过独立的创建索引语句来实现。此外,还详细讨论了NULL值在唯一索引中的处理方式。
2537

被折叠的 条评论
为什么被折叠?



