使用 ALTER 命令為 MySQL 表設定自動增量初始值


要為 MySQL 表設定自動增量初始值,請使用 ALTER 命令。第一步如下

alter table yourTableName modify yourColumnName int NOT NULL AUTO_INCREMENT PRIMARY KEY,add index(yourColumnName);

第二步如下

alter table yourTableName AUTO_INCREMENT=yourStartingValue;

為了理解以上語法,讓我們建立一個表。建立表的查詢如下

mysql> create table setAutoIncrementDemo
   -> (
   -> UserId int,
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (0.75 sec)

現在實施以上兩個步驟,為 MySQL 表設定自動增量初始值。

步驟 1 -查詢如下

mysql> alter table setAutoIncrementDemo modify UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,add index(UserId);
Query OK, 0 rows affected (1.51 sec)
Records: 0 Duplicates: 0 Warnings: 0

步驟 2 -查詢如下

mysql> alter table setAutoIncrementDemo AUTO_INCREMENT=1000;
Query OK, 0 rows affected (0.34 sec)
Records: 0 Duplicates: 0 Warnings: 0

使用插入命令在表中插入一些記錄。

查詢如下

mysql> INSERT INTO setAutoIncrementDemo(UserName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO setAutoIncrementDemo(UserName) values('Carol');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO setAutoIncrementDemo(UserName) values('Sam');
Query OK, 1 row affected (0.13 sec)

使用 select 語句顯示錶中的所有記錄。

查詢如下

mysql> select *from setAutoIncrementDemo;

以下是輸出

+--------+----------+
| UserId | UserName |
+--------+----------+
| 1000   | John     |
| 1001   | Carol    |
| 1002   | Sam      |
+--------+----------+
3 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

594 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告