在 MySQL 中新增特定列之後的另一列並定義預設值?


若要新增特定列之後的另一列並定義預設值,你需要按照一些步驟執行。為了實現此目的,你需要使用 ALTER 命令。我們首先建立一個表 -

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20),
   StudentAge int,
   StudentCountryName varchar(100)
   );
Query OK, 0 rows affected (0.21 sec)

讓我們查看錶的描述 -

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;
Query OK, 0 rows affected (0.91 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table DemoTable alter StudentLastName set default 'Doe';
Query OK, 0 rows affected (0.32 sec)
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)

更新於: 2019 年 7 月 30 日

1K+ 次瀏覽

開啟你的 職業生涯

完成課程認證

開始使用
廣告
© . All rights reserved.