如何使 MySQL 中的一对列唯一?(翻译)


要使一对列具有唯一性,请将 UNIQUE 与 ALTER TABLE 命令配合使用。以下为语法 −

alter table yourTableName add unique yourUniqueName(yourColumnName1,yourColumnName2,...N);

让我们首先创建一个表 −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(100),
   StudentLastName varchar(100),
   StudentAge int,
   StudentPhoneNumber varchar(20)
);
Query OK, 0 rows affected (0.81 sec)

以下是使 MySQL 中一对列具有唯一性的查询 −

mysql> alter table DemoTable add unique DemoTable_unique_StudentFirstName_StudentPhoneNumber(StudentFirstName,StudentPhoneNumber);
Query OK, 0 rows affected (0.40 sec)
Records: 0 Duplicates: 0 Warnings: 0

使用 insert 命令向表中插入一些记录 −

mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Doe',21,'9878567878');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Smith',23,'7654674545');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber)
values('John','Brown',21,'9878567878');
ERROR 1062 (23000): Duplicate entry 'John-9878567878' for key 'DemoTable_unique_StudentFirstName_StudentPhoneNumber'

使用 select 语句从表中显示所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentPhoneNumber |
+-----------+------------------+-----------------+------------+--------------------+
|         1 | John             | Doe             | 21         | 9878567878         |
|         2 | John             | Smith           | 23         | 7654674545         |
+-----------+------------------+-----------------+------------+--------------------+
2 rows in set (0.00 sec)

更新于: 25-Sep-2019(翻译)

658 次浏览(翻译)

开启你的 职业生涯

完成课程即可获得认证

立即开始
广告