在 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)

更新於:2019 年 12 月 24 日

322 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告