如果我忘記設定自動遞增怎麼辦?我可以在 MySQL 中稍後設定它嗎?


是的,您可以使用 ALTER table 在稍後設定自動遞增。讓我們首先建立一個表。在這裡,您可以看到,我們沒有設定自動遞增 -

mysql> create table forgetToSetAutoIncrementDemo
   -> (
   -> StudentId int,
   -> StudentName varchar(30)
   -> );
Query OK, 0 rows affected (1.17 sec)

現在檢查表描述,沒有 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;
Query OK, 0 rows affected (2.12 sec)
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');
Query OK, 1 row affected (0.16 sec)

mysql> insert into forgetToSetAutoIncrementDemo(StudentName) values('Chris');
Query OK, 1 row affected (0.13 sec)

mysql> insert into forgetToSetAutoIncrementDemo(StudentName) values('Robert');
Query OK, 1 row affected (0.17 sec)

以下是使用 select 語句顯示錶中所有記錄的查詢 -

mysql> select * from forgetToSetAutoIncrementDemo;

這將產生以下輸出,顯示 StudentID 作為自動遞增 -

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Larry       |
| 2         | Chris       |
| 3         | Robert      |
+-----------+-------------+
3 rows in set (0.00 sec)

更新於: 2019-07-30

119 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.