我们能在 MySQL 中强制复合唯一性吗?
是的,我们可以这样做。为了理解,我们首先创建一个表格 -
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) -> ); Query OK, 0 rows affected (0.60 sec)
以下是对表记录插入使用 insert 命令的查询 -
mysql> insert into enforceCompoundUniqueness(StudentName,StudentMobileNumber) values('Larry','2322245676'); Query OK, 1 row affected (0.18 sec) 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'); Query OK, 1 row affected (0.13 sec)
在上面的查询中,如果你尝试插入重复记录,你会看到一个错误,因为我们强制了唯一性。
以下是对使用 select 语句从表中显示所有记录的查询 -
mysql> select * from enforceCompoundUniqueness;
这将产生以下输出 -
+-----------+-------------+---------------------+ | StudentId | StudentName | StudentMobileNumber | +-----------+-------------+---------------------+ | 1 | Larry | 2322245676 | | 3 | Sam | 6475746455 | +-----------+-------------+---------------------+ 2 rows in set (0.00 sec)
广告