如何防止在MySQL中重复INSERT?

为此,您可以使用UNIQUE INDEX-

alter table yourTableName ADD UNIQUE INDEX(yourColumnName1, yourColumnName2,....N);

让我们首先创建一个表-

create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );

以下是添加唯一索引的查询-

alter table DemoTable ADD UNIQUE INDEX(Value1, Value2);
Records: 0  Duplicates: 0  Warnings: 0

使用插入命令在表中插入一些记录-

–使用INSERT IGNORE命令而不是INSERT命令。如果一条记录与现有记录不重复,则MySQL照常插入它。如果记录是重复的,则IGNORE关键字告诉MySQL静默丢弃它而不会产生错误。

insert ignore into DemoTable values(10,20);

insert ignore into DemoTable values(10,20);

使用select语句显示表中的所有记录-

select *from DemoTable;

输出结果

这将产生以下输出-

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   20   |
+--------+--------+
1 row in set (0.00 sec)