如何避免在MySQL中插入重复的行?

为了避免在MySQL中插入重复的行,可以使用UNIQUE()。语法如下-

ALTER TABLE yourTableName ADD UNIQUE(yourColumnName1,yourColumnName2,...N);

为了理解上述语法,让我们创建一个表。 

创建表的查询如下-

mysql> create table avoidInsertingDuplicateRows
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstValue int,
   -> SecondValue int
   -> );

现在使用desc命令检查表的描述。 

查询如下-

mysql> desc avoidInsertingDuplicateRows;

示例以下是输出-

+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| Id          | int(11) | NO   | PRI | NULL    | auto_increment |
| FirstValue  | int(11) | YES  |     | NULL    |                |
| SecondValue | int(11) | YES  |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

这是避免在MySQL中插入重复行的查询。我们将使用insert命令设置它以在表中插入记录-

mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
ERROR 1062 (23000): Duplicate entry '10-20' for key 'FirstValue'

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

查询如下-

mysql> select *from avoidInsertingDuplicateRows;

这是输出-

+----+------------+-------------+
| Id | FirstValue | SecondValue |
+----+------------+-------------+
| 1  | 10         | 20          |
+----+------------+-------------+
1 row in set (0.00 sec)