ALTER TABLE <表名> ADD <新字段名><数据类型>[约束条件];
对语法格式的说明如下:注意:本节我们只添加新的字段,不关注它的约束条件。
mysql> USE test; Database changed mysql> CREATE TABLE student ( -> id INT(4), -> name VARCHAR(20), -> sex CHAR(1)); Query OK, 0 rows affected (0.09 sec)
mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 3 rows in set (0.01 sec)
mysql> ALTER TABLE student ADD age INT(4); Query OK, 0 rows affected (0.16 sec) Records: 0 Duplicates: 0 Warnings: 0
mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)由运行结果可以看到,student 表已经添加了 age 字段,且该字段在表的最后一个位置,添加字段成功。
ALTER TABLE <表名> ADD <新字段名> <数据类型> [约束条件] FIRST;
FIRST 关键字一般放在语句的末尾。mysql> ALTER TABLE student ADD stuId INT(4) FIRST; Query OK, 0 rows affected (0.14 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | stuId | int(4) | YES | | NULL | | | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 5 rows in set (0.00 sec)由运行结果可以看到,student 表中已经添加了 stuId 字段,且该字段在表中的第一个位置,添加字段成功。
ALTER TABLE <表名> ADD <新字段名> <数据类型> [约束条件] AFTER <已经存在的字段名>;
AFTER 的作用是将新字段添加到某个已有字段后面。mysql> ALTER TABLE student ADD stuno INT(11) AFTER name; Query OK, 0 rows affected (0.13 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | stuId | int(4) | YES | | NULL | | | id | int(4) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | stuno | int(11) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | age | int(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 6 rows in set (0.00 sec)由运行结果可以看到,student 表中已经添加了 stuId 字段,且该字段在 name 字段后面的位置,添加字段成功。
本文链接:http://task.lmcjl.com/news/18702.html