为了防止两次插入项目组合,请更改表并为列设置UNIQUE,如以下语法所示:
alter table yourTableName add constraint yourConstraintName unique(yourColumnName1,yourColumnName2,....N);
让我们首先创建一个表-
mysql> create table DemoTable ( Value1 int, Value2 int );
这是防止项目组合插入两次的查询-
mysql> alter table DemoTable add constraint Value1_Value2_ConstraintKey unique(Value1,Value2); Records : 0 Duplicates : 0 Warnings : 0
使用insert命令在表中插入一些记录。在这里,当我们尝试插入重复组合时,会出现错误“重复条目”,并且重复插入将无法进行-
mysql> insert into DemoTable values(10,10); mysql> insert into DemoTable values(10,20); 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); mysql> insert into DemoTable values(20,20); 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)