如何防止MySQL双重插入(重复记录)?
为了防止重复记录,可以添加UNIQUE约束。让我们首先创建一个表−
mysql> create table DemoTable
(
Id int,
Name varchar(100)
);
Query OK, 0 rows affected (0.79 sec)
下面是使用UNIQUE防止MySQL双重插入的查询语句−
mysql> alter table DemoTable add constraint id_NameUnKey UNIQUE(Id,Name);
Query OK, 0 rows affected (0.82 sec)
Records: 0 Duplicates: 0 Warnings: 0
使用insert命令向表中插入记录。当我们再次尝试插入相同的记录时,将会出现“重复记录”错误−
mysql> insert into DemoTable values(11,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(12,'John');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(11,'John');
ERROR 1062 (23000): Duplicate entry '11-John' for key 'id_NameUnKey'
使用select命令显示表中的记录−
mysql> select *from DemoTable;
将会产生以下输出−
+------+------+
| Id | Name |
+------+------+
| 11 | John |
| 12 | John |
+------+------+
2 rows in set (0.00 sec)
阅读更多:MySQL 教程
极客教程