在 MySQL 中用 Key=MUL 创建列?
需要使用 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) -> ); Query OK, 0 rows affected (0.63 sec)
现在你可以查看表描述,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)
以下是使用 Key=MUL 在 MySQL 中创建列的查询。将列 `Instructor_Id` 设为 Key=MUL。查询如下 -
mysql> alter table Instructor modify column Instructor_Id int NOT NULL AUTO_INCREMENT, -> add key(Instructor_Id); Query OK, 0 rows affected (2.88 sec) 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); Query OK, 0 rows affected (2.77 sec) 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)
广告