如何在 MySQL 中创建唯一的复合键?


要形成唯一复合键,需要使用 ADD UNIQUE 命令。以下是语法:−

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

让我们首先创建一个表。以下是查询:−

mysql> create table makeCompositeKeyDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40),
   -> StudentAge int,
   -> StudentGrade char(1)
   -> );
Query OK, 0 rows affected (2.34 sec)

现在使用 DESC 命令检查表的描述。以下是查询:−

mysql> desc makeCompositeKeyDemo;

这将产生以下输出:−

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  |     | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (1.65 sec)

以下是形成唯一复合键的查询:−

mysql> alter table makeCompositeKeyDemo add unique
Name_Age_Grade( StudentName,StudentAge,StudentGrade);
Query OK, 0 rows affected (0.69 sec)
Records: 0 Duplicates: 0 Warnings: 0

现在再次检查表描述。以下是查询:−

mysql> desc makeCompositeKeyDemo;

这将产生以下输出:−

+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  | MUL | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

更新日期: 30-Jul-2019

1K+ 浏览

加速您的职业生涯

完成课程,即可获得认证

开始
广告
© . All rights reserved.