如何在带有某些条件的 MySQL 字符串变量列中使用 UNIQUE?
为此,您可以在一个或多个列上使用 UNIQUE 约束——
alter table yourTablleName add unique(yourColumnName1,yourColumnName2,...N);
我们先创建一个表——
mysql> create table DemoTable1598 -> ( -> EmployeeId int, -> EmployeeName varchar(20), -> EmployeeCountryName varchar(20) -> ); Query OK, 0 rows affected (0.52 sec)
这是在 varchar 列上实现 UNIQUE 的查询——
mysql> alter table DemoTable1598 add unique(EmployeeName,EmployeeCountryName); Query OK, 0 rows affected (0.55 sec) Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录——
mysql> insert into DemoTable1598 values(101,'Adam','AUS'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1598 values(102,'John','US'); Query OK, 1 row affected (0.64 sec) mysql> insert into DemoTable1598 values(103,'Adam','US'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1598 values(104,'Adam','AUS'); ERROR 1062 (23000): Duplicate entry 'Adam-AUS' for key 'EmployeeName'
使用选择语句在表中显示所有记录——
mysql> select * from DemoTable1598;
这将产生以下输出——
+------------+--------------+---------------------+ | EmployeeId | EmployeeName | EmployeeCountryName | +------------+--------------+---------------------+ | 101 | Adam | AUS | | 102 | John | US | | 103 | Adam | US | +------------+--------------+---------------------+ 3 rows in set (0.00 sec)
广告