如何將 MySQL 中的主鍵更改為自動增量?
要將主鍵更改為自動增量,可以使用 MODIFY 命令。我們先建立一個表。
mysql> create table changePrimaryKeyInAutoIncrement -> ( -> StudentId int not null primary key, -> StudentName varchar(100), -> StudentAge int, -> StudentAddress varchar(100) -> ); Query OK, 0 rows affected (0.63 sec)
現在讓我們使用 desc 命令檢查表的描述
mysql> desc changePrimaryKeyInAutoIncrement;
這樣會產生以下輸出
+----------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+-------+ | StudentId | int(11) | NO | PRI | NULL | | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+-------+ 4 rows in set (0.00 sec)
看看上面的示例輸出,StudentId 列是主鍵。現在讓我們將主鍵更改為自動增量
mysql> alter table changePrimaryKeyInAutoIncrement MODIFY StudentId INT AUTO_INCREMENT; Query OK, 0 rows affected (1.48 sec) Records: 0 Duplicates: 0 Warnings: 0
讓我們再次檢查表描述
mysql> desc changePrimaryKeyInAutoIncrement;
這樣會產生以下輸出
+----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(100) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentAddress | varchar(100) | YES | | NULL | | +----------------+--------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)
看看上面的示例輸出,StudentId 列已被更改為自動增量。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP