首頁  >  文章  >  資料庫  >  我們如何更改MySQL AUTO_INCRMENT起始編號?

我們如何更改MySQL AUTO_INCRMENT起始編號?

PHPz
PHPz轉載
2023-09-02 22:25:111064瀏覽

我们如何更改MySQL AUTO_INCRMENT起始编号?

MySQL AUTO_INCRMENT 值從1 開始,但我們可以透過以下兩種方式更改它-

借助ALTER TABLE 查詢

#我們可以使用ALTER TABLE 查詢更改AUTO_INCRMENT 的起始值,如下所示-

ALTER TABLE table_name AUTO_INCREMENT = value;

Example

的中文翻譯為:

範例

Suppose we have created a table having column 'id' as AUTO_INCREMENT. Now if we will insert the values in it then the sequence number would start from 1 as you can see this in following queries −

mysql> Create Table EMP(id int NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(10));
Query OK, 0 rows affected (0.07 sec)

mysql> Insert Into EMP(Name) Values('Aryan');
Query OK, 1 row affected (0.02 sec)

mysql> Insert Into EMP(Name) Values('Yash');
Query OK, 1 row affected (0.04 sec)

mysql> Select * from EMP;
+----+-------+
| id | NAME  |
+----+-------+
| 1  | Aryan |
| 2  | Yash  |
+----+-------+
2 rows in set (0.00 sec)

現在,如果我們想要在之後更改序號,我們需要更改序號,我們需要使用ALTER TABLE查詢來更改AUTO_INCREMENT的值,如下所示−

mysql> Alter table emp auto_increment = 10;
Query OK, 2 rows affected (0.25 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> Insert Into EMP(Name) Values('Daksh');
Query OK, 1 row affected (0.03 sec)

mysql> Insert Into EMP(Name) Values('Shayra');
Query OK, 1 row affected (0.06 sec)

mysql> Select * from EMP;
+----+--------+
| id | NAME   |
+----+--------+
| 1  | Aryan  |
| 2  | Yash   |
| 10 | Daksh  |
| 11 | Shayra |
+----+--------+
4 rows in set (0.00 sec)

上面的查詢已將AUTO_INCRMENT 的值更改為10,因此在插入新值後,我們將獲得從10 開始的序號。

借助 CREATE TABLE 查詢

我們也可以在建立表格時變更 AUTO_INCRMENT 值。可以透過使用CREATE TABLE 查詢指定AUTO_INCRMENT 的值來完成,如下所示-

CREATE TABLE (Column1 INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Column2 data type) AUTO_INCREMENT = value;

Example

的中文翻譯為:

範例

mysql> Create Table EMP1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(10)) AUTO_INCREMENT = 100;
Query OK, 0 rows affected (0.11 sec)

上述查詢在建立表格時將AUTO_INCREMENT的值指定為100。現在,如果我們將值插入其中,則序號將從100開始,而不是預設值1,如下所示 −

mysql> Insert into emp1(name) values('Sohan');
Query OK, 1 row affected (0.04 sec)

mysql> Insert into emp1(name) values('Harshit');
Query OK, 1 row affected (0.05 sec)

mysql> Select * from emp1;
+-----+---------+
| id  | NAME    |
+-----+---------+
| 100 |   Sohan |
| 101 | Harshit |
+-----+---------+
2 rows in set (0.00 sec)

以上是我們如何更改MySQL AUTO_INCRMENT起始編號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除