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

mysqlmysqli database更新于 2025/3/31 1:16:17

为了避免在 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
   -> );
Query OK, 0 rows affected (0.53 sec)

现在使用 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);
Query OK, 1 row affected (0.24 sec)
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)

相关文章


有用资源