是的,您可以稍后使用ALTER表设置“自动增量”。让我们首先创建一个表。如您所见,在这里,我们没有设置自动增量-
mysql> create table forgetToSetAutoIncrementDemo -> ( -> StudentId int, -> StudentName varchar(30) -> );
现在检查表描述,没有auto_increment列-
mysql> desc forgetToSetAutoIncrementDemo;
这将产生以下输出-
+-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | StudentId | int(11) | YES | | NULL | | | StudentName | varchar(30) | YES | | NULL | | +-------------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec)
以下是在StudentId列上设置自动增量的查询-
mysql> alter table forgetToSetAutoIncrementDemo modify column StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY; Records: 0 Duplicates: 0 Warnings: 0
现在再次检查表描述,成功添加了auto_increment列-
mysql> desc forgetToSetAutoIncrementDemo;
这将产生以下输出-
+-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | StudentId | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(30) | YES | | NULL | | +-------------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
以下是使用insert命令在表中插入一些记录的查询-
mysql> insert into forgetToSetAutoIncrementDemo(StudentName) values('Larry'); mysql> insert into forgetToSetAutoIncrementDemo(StudentName) values('Chris'); mysql> insert into forgetToSetAutoIncrementDemo(StudentName) values('Robert');
以下是使用select语句显示表中所有记录的查询-
mysql> select * from forgetToSetAutoIncrementDemo;
这将产生以下输出,显示StudentID为auto_increment-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Larry | | 2 | Chris | | 3 | Robert | +-----------+-------------+ 3 rows in set (0.00 sec)