在MySQL中向ALTER TABLE添加唯一约束
让我们首先创建一个表-
mysql> create table DemoTable1811(
FirstName varchar(20),
LastName varchar(20)
);
这是要添加索引的查询
mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName);Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1811 values('John','Smith');mysql> insert into DemoTable1811 values('John','Doe');
mysql> insert into DemoTable1811 values('Adam','Smith');
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)
以上是 在MySQL中向ALTER TABLE添加唯一约束 的全部内容, 来源链接: utcz.com/z/326683.html