如何讓主鍵從 1000 開始?


要讓主鍵從 1000 開始,你需要更改你的表,並使用值為 1000 的自動遞增。語法如下 -

alter table yourTableName auto_increment=1000;

為了理解上述語法,讓我們先建立一個表。建立表的查詢如下 -

mysql> create table PrimaryKey1000Demo
   -> (
   -> ProductId int auto_increment,
   -> PRIMARY KEY(ProductId)
   -> );
Query OK, 0 rows affected (0.56 sec)

現在,以下查詢將更新主鍵,使其從 1000 開始 -

mysql> alter table PrimaryKey1000Demo auto_increment=1000;
Query OK, 0 rows affected (0.20 sec)
Records: 0 Duplicates: 0 Warnings: 0

現在,我們已將起始值更新為從 1000 開始。現在讓我們插入一些記錄,以檢查主鍵的起始值。插入記錄的查詢如下 -

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.11 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.19 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.23 sec)

mysql> insert into PrimaryKey1000Demo values();
Query OK, 1 row affected (0.08 sec)

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

mysql> select *from PrimaryKey1000Demo;

以下是輸出,顯示從 1000 開始的產品 ID,即我們的主鍵 -

+-----------+
| ProductId |
+-----------+
|      1000 |
|      1001 |
|      1002 |
|      1003 |
+-----------+
4 rows in set (0.00 sec)

更新於: 2020 年 6 月 25 日

2K+ 次瀏覽

啟動您的事業

完成課程以獲得認證

立即開始
廣告
© . All rights reserved.