在 MySQL 中使用 ALTER TABLE 添加唯一约束
让我们首先创建一个表 -
mysql> create table DemoTable1811 ( FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
以下是添加索引的查询
mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName); Query OK, 0 rows affected (0.00 sec) Records: 0 Duplicates: 0 Warnings: 0
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1811 values('John','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('Adam','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1811 values('John','Doe'); ERROR 1062 (23000): Duplicate entry 'John-Doe' for key 'unique_index_first_last_name'
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1811;
这将产生以下输出 -
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Adam | Smith | | John | Doe | | John | Smith | +-----------+----------+ 3 rows in set (0.00 sec)
广告