防止專案組合在 MySQL 中重複插入?


要防止專案組合被重複插入,請更改表並在列中設定 UNIQUE,如以下語法所示 −

alter table yourTableName add constraint yourConstraintName unique(yourColumnName1,yourColumnName2,....N);

讓我們先建立一個表 −

mysql> create table DemoTable
(
   Value1 int,
   Value2 int
);
Query OK, 0 rows affected (0.47 sec)

以下是如何防止專案組合被重複插入的查詢 −

mysql> alter table DemoTable add constraint Value1_Value2_ConstraintKey unique(Value1,Value2);
Query OK, 0 rows affected (0.80 sec)
Records : 0 Duplicates : 0 Warnings : 0

使用 insert 命令向表中插入一些記錄。在此處,當我們嘗試插入重複組合時,會出現 “Duplicate entry” 錯誤,並且重複插入將不起作用 −

mysql> insert into DemoTable values(10,10);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(10,20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(10,10);
ERROR 1062 (23000) : Duplicate entry '10-10' for key 'Value1_Value2_ConstraintKey'
mysql> insert into DemoTable values(20,10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(20,20);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(20,10);
ERROR 1062 (23000) : Duplicate entry '20-10' for key 'Value1_Value2_ConstraintKey'

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將生成以下輸出 −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |     10 |
|     10 |     20 |
|     20 |     10 |
|     20 |     20 |
+--------+--------+
4 rows in set (0.00 sec)

更新於: 10-Oct-2019

260 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.