如何在 MySQL 中已创建的表中插入 auto_increment?

mysqlmysqli database

使用 ALTER 命令。让我们首先创建一个表 −

mysql> create table DemoTable
-> (
-> StudentName varchar(100)
-> );
Query OK, 0 rows affected (0.46 sec)

这是插入 auto_increment 的查询 −

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)

相关文章