如何防止在 MySQL 表中输入重复的条目?
若要防止在 MySQL 表中输入重复条目,你需要添加唯一键。以下是该语法的示例 −
alter ignore table yourTableName add constraint unique key(yourColumName);
上述语法设置了唯一键。若要理解上述语法,让我们创建一个表。
以下是创建表的查询 −
mysql> create table RemoveDuplicateEntry −> ( −> Id int, −> Name varchar(100) −> )ENGINE = MyISAM; Query OK, 0 rows affected (0.15 sec)
现在,你可以实现文章开篇时所讨论的语法。查询如下 −
mysql> alter table RemoveDuplicateEntry add constraint unique key(Id); Query OK, 0 rows affected (0.56 sec) Records: 0 Duplicates: 0 Warnings: 0
现在,让我们查看表结构。查询如下 −
mysql> desc RemoveDuplicateEntry;
以下是输出 −
+-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | Id | int(11) | YES | UNI | NULL | | | Name | varchar(100) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
现在,让我们插入一些带有重复条目的记录。由于我们在上面使用了 UNIQUE,所以这些条目不会被插入 −
插入记录的查询如下 −
mysql> insert into RemoveDuplicateEntry values(101,'John'); Query OK, 1 row affected (0.06 sec)
现在,如果你要再次插入相同的记录,那么将会看到以下错误 −
mysql> insert into RemoveDuplicateEntry values(101,'John'); ERROR 1062 (23000): Duplicate entry '101' for key 'Id'
使用 select 语句查看表中的所有记录。查询如下 −
mysql> select *from RemoveDuplicateEntry;
以下是输出,显示不带重复条目的记录 −
+------+------+ | Id | Name | +------+------+ | 101 | John | +------+------+ 1 row in set (0.00 sec)
广告