为此,您可以在一个或多个列上使用UNIQUE约束-
alter table yourTablleName add unique(yourColumnName1,yourColumnName2,...N);
让我们首先创建一个表-
mysql> create table DemoTable1598 -> ( -> EmployeeId int, -> EmployeeName varchar(20), -> EmployeeCountryName varchar(20) -> );
这是在varchar列上实现UNIQUE的查询-
mysql> alter table DemoTable1598 add unique(EmployeeName,EmployeeCountryName); Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1598 values(101,'Adam','AUS'); mysql> insert into DemoTable1598 values(102,'John','US'); mysql> insert into DemoTable1598 values(103,'Adam','US'); mysql> insert into DemoTable1598 values(104,'Adam','AUS'); ERROR 1062 (23000): Duplicate entry 'Adam-AUS' for key 'EmployeeName'
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1598;
这将产生以下输出-
+------------+--------------+---------------------+ | EmployeeId | EmployeeName | EmployeeCountryName | +------------+--------------+---------------------+ | 101 | Adam | AUS | | 102 | John | US | | 103 | Adam | US | +------------+--------------+---------------------+ 3 rows in set (0.00 sec)