使用 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)
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP