MySQL如何形成一个唯一的组合键

MySQL如何形成一个唯一的组合键

要形成一个唯一的组合键,您需要使用ADD UNIQUE命令。以下是语法-

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

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

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)
Mysql

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

mysql> desc makeCompositeKeyDemo;
Mysql

这将产生如下输出-

+--------------+-------------+------+-----+---------+----------------+
| 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

以下是形成一个唯一的组合键的查询-

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

现在再次检查表的描述。以下是查询-

mysql> desc makeCompositeKeyDemo;
Mysql

这将产生如下输出-

+--------------+-------------+------+-----+---------+----------------+
| 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)
Mysql

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册