要将新的枚举列添加到现有的MySQL表中,可以使用ALTER命令。以下是语法:
ALTER TABLE yourTableName ADD yourColumnName ENUM('yourValue1','yourValue2’....N) NOT NULL;
让我们首先创建一个表:
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(200), StudentAge int );
使用DESC命令检查表的描述:
mysql> DESC DemoTable;
这将产生以下输出:
+-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(200) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec)
以下是向现有表添加新的枚举列的查询。我们为学生性别设置了它:
mysql> ALTER TABLE DemoTable ADD StudentGender ENUM('Male','Female') NOT NULL; Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述:
mysql> desc DemoTable;
这将产生以下输出并显示GENDER的枚举值:
+---------------+-----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-----------------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(200) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentGender | enum('Male','Female') | NO | | NULL | | +---------------+-----------------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
查看上面的示例输出,StudentGender列的数据类型为ENUM。