您需要使用ADD KEY来创建Key = MUL的列。语法如下-
ALTER TABLE yourTableName MODIFY COLUMN yourColumnName data type, ADD KEY(yourColumnName);
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table Instructor -> ( -> Instructor_Id int, -> Instructor_Name varchar(30), -> Instructor_CourseName varchar(100) -> );
现在,您可以查看表的表说明,KEY列没有任何MUL键。查询如下,以使用DESC命令检查表的描述。
mysql> desc Instructor;
以下是输出-
+-----------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+--------------+------+-----+---------+-------+ | Instructor_Id | int(11) | YES | | NULL | | | Instructor_Name | varchar(30) | YES | | NULL | | | Instructor_CourseName | varchar(100) | YES | | NULL | | +-----------------------+--------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
这是在MySQL中使用Key = MUL创建一列的查询。将“ Instructor_Id”列设为Key = MUL。查询如下-
mysql> alter table Instructor modify column Instructor_Id int NOT NULL AUTO_INCREMENT, -> add key(Instructor_Id); Records: 0 Duplicates: 0 Warnings: 0
现在再次检查表说明。查询如下-
mysql> desc Instructor;
以下是输出-
+-----------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+--------------+------+-----+---------+----------------+ | Instructor_Id | int(11) | NO | MUL | NULL | auto_increment | | Instructor_Name | varchar(30) | YES | | NULL | | | Instructor_CourseName | varchar(100) | YES | | NULL | | +-----------------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)
要添加非主键,您需要使用以下查询-
mysql> alter table Instructor modify column Instructor_Name varchar(30) NOT NULL, -> add key(Instructor_Name); Records: 0 Duplicates: 0 Warnings: 0
现在再次检查表说明。查询如下-
mysql> desc Instructor;
以下是显示其中一个字段的Key为MUL的输出-
+-----------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------------+--------------+------+-----+---------+----------------+ | Instructor_Id | int(11) | NO | MUL | NULL | auto_increment | | Instructor_Name | varchar(30) | NO | MUL | NULL | | | Instructor_CourseName | varchar(100) | YES | | NULL | | +-----------------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)