向现有 MySQL 表添加新枚举列?
mysqlmysqli database更新于 2024/10/18 9:48:17
要向现有 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 ); Query OK, 0 rows affected (0.62 sec)
使用 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;
Query OK, 0 rows affected (0.40 sec)
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。
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

