在 MySQL 表中插入重复记录时显示错误

mysqlmysqli database

为此,您可以使用 UNIQUE KEY。让我们首先创建一个表 −

mysql> create table DemoTable1553
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20),
   -> EmployeeSalary int
   -> );
Query OK, 0 rows affected (0.47 sec)

这是添加唯一键的查询 −

mysql> alter table DemoTable1553 add unique(EmployeeSalary);
Query OK, 0 rows affected (0.53 sec)
Records: 0  Duplicates: 0  Warnings: 0

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Chris',45000);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1553(EmployeeName,EmployeeSalary) values('David',35000);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Sam',25000);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Carol',45000);
ERROR 1062 (23000): Duplicate entry '45000' for key 'EmployeeSalary'

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

mysql> select * from DemoTable1553;

这将产生以下输出 −

+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
|          1 | Chris        |          45000 |
|          2 | David        |          35000 |
|          3 | Sam          |          25000 |
+------------+--------------+----------------+
3 rows in set (0.00 sec)

相关文章