数据库
首页 > 数据库> > mysql – SQL创建表并设置不带Alter表的自动增量值

mysql – SQL创建表并设置不带Alter表的自动增量值

作者:互联网

例如,我正在创建下表:

CREATE TABLE Persons (

     ID int NOT NULL AUTO_INCREMENT,

     LastName
varchar(255) NOT NULL,

     FirstName varchar(255),
     Address varchar(255),
     PRIMARY KEY (ID)
)

据我所知,自动增量的值可以通过这样的Alter表修改

ALTER TABLE Persons AUTO_INCREMENT=100;

但我只是想知道有没有办法在创建表时设置自动增量的值?像这样的东西?

CREATE TABLE Persons (

     ID int NOT NULL AUTO_INCREMENT = 100,

     LastName
varchar(255) NOT NULL,

     FirstName varchar(255),
     Address varchar(255),
     PRIMARY KEY (ID)
)

解决方法:

是的,您可以在创建表格时执行此操作

CREATE TABLE Persons (
     ID int NOT NULL AUTO_INCREMENT,
     LastName varchar(255) NOT NULL,
     FirstName varchar(255),
     Address varchar(255),
     PRIMARY KEY (ID)
)AUTO_INCREMENT=100;

这是一个测试用例

mysql> CREATE TABLE Persons (
    ->      ID int NOT NULL AUTO_INCREMENT,
    ->      LastName varchar(255) NOT NULL,
    ->      FirstName varchar(255),
    ->      Address varchar(255),
    ->      PRIMARY KEY (ID)
    -> )AUTO_INCREMENT=100;
Query OK, 0 rows affected (0.13 sec)

mysql> insert into Persons (LastName) values ('CCC');
Query OK, 1 row affected (0.03 sec)

mysql> select * from Persons ;
+-----+----------+-----------+---------+
| ID  | LastName | FirstName | Address |
+-----+----------+-----------+---------+
| 100 | CCC      | NULL      | NULL    |
+-----+----------+-----------+---------+
1 row in set (0.00 sec)

标签:mysql,create-table
来源: https://codeday.me/bug/20190717/1489675.html