在 MySQL 中使现有字段唯一?

在 MySQL 中使现有字段唯一?

MySQL 中的独特性意味着我们不能添加重复的记录。现在让我们看看如何在创建表时在列中创建唯一约束。

mysql> create table UniqueConstDemo - > ( - > name varchar(100) unique - > ); Query OK, 0 rows affected (0.72 sec)登录后复制

插入一些具有重复值的记录来检查错误。

mysql> insert into UniqueConstDemo values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into UniqueConstDemo values('John');登录后复制

mysql> insert into UniqueConstDemo values('John'); ERROR 1062 (23000): Duplicate entry 'John' for key 'name'登录后复制

mysql> insert into UniqueConstDemo values('Bob'); Query OK, 1 row affected (0.11 sec)登录后复制

mysql> select *from UniqueConstDemo; 登录后复制

+-------+ | name | +-------+ | Bob | | John | +-------+ 3 rows in set (0.00 sec)登录后复制