如何避免在 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 -> ); 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)
廣告