mysql 自增_mysql自增

时间:2025-03-31 22:52:19

表结构

CREATE TABLE `salary` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`user_id` int(11) NOT NULL DEFAULT '0',

`salary` decimal(10,2) NOT NULL DEFAULT '0',

PRIMARY KEY (`id`)

)

auto_increment

# 查看当前表的auto_increment值

mysql> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='db_name' and TABLE_NAME='table_name';

# 修改当前auto_increment值

mysql> alter table db_name.table_name auto_increment=20

对auto_increment的理解

如果插入数据库时不指定auto_increment字段的值,那么该字段为auto_increment当前的值,然后 auto_increment自增1

如果插入数据库时指定了auto_increment字段的值,并且指定的值小于等于当前auto_increment的值(指定的值无重复),插入成功,但是auto_increment不会自增

如果插入数据库时指定了auto_increment字段的值,并且指定的值大于当前auto_increment的值,插入成功,auto_increment变为指定值加1

当前最大id大于auto_increment的值,插入时不指定auto_increment字段值,当自增id等于最大id时,会插入失败,然后auto_increment自增1

last_insert_id()

不带参数时,该函数返回最近一个insert语句生成的第一个自动增长列的值,值为bigint unsigned类型。

带参数时,返回一个unsigned int。

# 查看自增值

mysql> select last_insert_id();

-> 20

last_insert_id是几月每个服务连接的,即一个服务的insert语句不会影响到另一个服务的last_insert_id的值,虽然他们共享auto_increment。如下例

# 连接1

mysql server1> insert into salary (user_id,salary) value(4,32);

mysql server1> select last_insert_id();

-> 5;

mysql server1> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='test' and TABLE_NAME='salary';

-> 6;

# 连接2

mysql server2> select last_insert_id();

-> 0;

mysql server2> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='test' and TABLE_NAME='salary';

-> 6;

当插入的值中包含了自增列,那么last_insert_id不会更新,但是会更新auto_increment的值

mysql> select last_insert_id();

-> 5

mysql> insert into salary (id,user_id,salary) value(8,4,32);

mysql> select last_insert_id();

-> 5

mysql> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='test' and TABLE_NAME='salary';

-> 9

一次插入多条数据,last_insert_id返回第一条成功插入后生成的id

mysql> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='test' and TABLE_NAME='salary';

-> 9

mysql> insert into salary (user_id,salary) values (4,32),(5,44);

mysql> select last_insert_id();

-> 9

mysql> select auto_increment from information_schema.TABLES WHERE TABLE_SCHEMA='test' and TABLE_NAME='salary';

-> 11

last_insert_id(expr),指定一个表达式参数,该表达式的返回值会当做下一次调用last_insert_id的返回值。

mysql> update salary set id=last_insert_id(id+3) where id=5;

mysql> select last_insert_id();

-> 8

参考链接