您需要按照一些步骤在特定列之后添加新列并定义默认值。为了实现这一点,您需要使用ALTER命令。让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentAge int, StudentCountryName varchar(100) );
让我们检查表的描述-
mysql> desc DemoTable;
这将产生以下输出-
+--------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentFirstName | varchar(20) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentCountryName | varchar(100) | YES | | NULL | | +--------------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.15 sec)
以下是在特定列之后添加新列并定义默认值的查询。让我们在列名称“ StudentFirstName”之后添加新列“ StudentLastName”。StudentLastName列的默认值为“ Doe”。
mysql> alter table DemoTable add StudentLastName varchar(20) NOT NULL after StudentFirstName; Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table DemoTable alter StudentLastName set default 'Doe'; Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述。
mysql> desc DemoTable;
这将产生以下输出-
+--------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentFirstName | varchar(20) | YES | | NULL | | | StudentLastName | varchar(20) | NO | | Doe | | | StudentAge | int(11) | YES | | NULL | | | StudentCountryName | varchar(100) | YES | | NULL | | +--------------------+--------------+------+-----+---------+----------------+ 5 rows in set (0.01 sec)