为此,您可以使用UNIQUE KEY。让我们首先创建一个表-
create table DemoTable1553 -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20), -> EmployeeSalary int -> );
这是添加唯一键的查询-
alter table DemoTable1553 add unique(EmployeeSalary); Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录-
insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Chris',45000); insert into DemoTable1553(EmployeeName,EmployeeSalary) values('David',35000); insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Sam',25000); insert into DemoTable1553(EmployeeName,EmployeeSalary) values('Carol',45000); ERROR 1062 (23000): Duplicate entry '45000' for key 'EmployeeSalary'
使用select语句显示表中的所有记录-
select * from DemoTable1553;
这将产生以下输出-
+------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Chris | 45000 | | 2 | David | 35000 | | 3 | Sam | 25000 | +------------+--------------+----------------+ 3 rows in set (0.00 sec)