使用 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 次浏览

开启您的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.