MySQL AUTO_INCRMENT 值从 1 开始,但我们可以通过以下两种方式更改它 -
我们可以使用ALTER TABLE 查询更改 AUTO_INCRMENT 的起始值,如下所示 -
ALTER TABLE table_name AUTO_INCREMENT = value;
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 开始的序列号。
我们还可以在创建表时更改 AUTO_INCRMENT 值。可以通过使用 CREATE TABLE 查询指定 AUTO_INCRMENT 的值来完成,如下所示 -
CREATE TABLE (Column1 INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Column2 data type) AUTO_INCREMENT = value;
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中文网其他相关文章!