如何防止MySQL INSERT中出现重复行?
为此,您需要对列使用UNIQUEKEY。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(30), UNIQUE KEY(FirstName) );
使用insert命令在表中插入一些记录。现在,我们还插入了“David”之类的重复记录,但是由于将列设置为UNIQUEKEY,所以不会插入两次-
mysql> insert ignore into DemoTable(FirstName) values('Chris'); mysql> insert ignore into DemoTable(FirstName) values('David'); mysql> insert ignore into DemoTable(FirstName) values('Chris'); mysql> insert ignore into DemoTable(FirstName) values('Sam'); mysql> insert ignore into DemoTable(FirstName) values('David');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | David | | 4 | Sam | +----+-----------+ 3 rows in set (0.00 sec)