如何在 MySQL 中为已创建的表插入自动增量值?
为此,请使用 ALTER 命令。我们先创建一个表 -
mysql> create table DemoTable -> ( -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.46 sec)
以下是如何插入自动增量的查询 -
mysql> alter table DemoTable ADD COLUMN StudentId int NOT NULL; Query OK, 0 rows affected (0.50 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table DemoTable ADD PRIMARY KEY(StudentId); Query OK, 0 rows affected (1.23 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table DemoTable CHANGE StudentId StudentId int NOT NULL AUTO_INCREMENT; Query OK, 0 rows affected (2.20 sec) Records: 0 Duplicates: 0 Warnings: 0
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentName) values('David'); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录
mysql> select *from DemoTable;
输出
这会生成以下输出 -
+-------------+-----------+ | StudentName | StudentId | +-------------+-----------+ | Chris | 1 | | David | 2 | +-------------+-----------+ 2 rows in set (0.00 sec)
广告