是的,我们可以做到。要了解,让我们首先创建一个表-
mysql> create table enforceCompoundUniqueness -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(40) NOT NULL, -> StudentMobileNumber varchar(12) NOT NULL, -> UNIQUE StudentName_StudentMobileNumber(StudentName,StudentMobileNumber) -> );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber) values('Larry','2322245676'); mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber) values('Larry','2322245676'); ERROR 1062 (23000): Duplicate entry 'Larry-2322245676' for key 'StudentName_StudentMobileNumber' mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber) values('Sam','6475746455');
在上面的查询中,如果您尝试插入重复记录,则由于我们已强制执行唯一性,因此会看到错误。
以下是使用select语句显示表中所有记录的查询-
mysql> select * from enforceCompoundUniqueness;
这将产生以下输出-
+-----------+-------------+---------------------+ | StudentId | StudentName | StudentMobileNumber | +-----------+-------------+---------------------+ | 1 | Larry | 2322245676 | | 3 | Sam | 6475746455 | +-----------+-------------+---------------------+ 2 rows in set (0.00 sec)