MySQL之last_insert_id()
在向数据库具有自增列的表中插入一行之后,会生成一个AUTO_INCREMENT值,可以通过SELECT LAST_INSERT_ID()得到这个值,返回BIGINT UNSIGNED (64-bit) 类型,注意是生成(generate)AUTO_INCREMENT值,如果是插入时自增字段的值是插入的而不是生成的,则不会。
模拟过程
现创建如下两张表
create table in_num
(
num_id int primary key auto_increment,
num_val int
);
create table in_num_2
(
num_id int primary key auto_increment,
num_val int
);
此时查询,显示结果为0
select last_insert_id();
向第一张表 in_num 中插入一行记录,并查询ast_insert_id(),可以看到结果为1,即该表该记录num_id字段值
insert into in_num(num_val) values (100);
select last_insert_id();

向第二张表 in_num_2 中插入一行记录,并查询ast_insert_id(),可以看到结果也为1,即该表该记录num_id字段值
insert into in_num_2(num_val) values (1000);

继续向 in_num_2 表中插入记录

可以看到 last_insert_id() 为in_num_2 表中刚插入记录生成的自增字段的值

我们此时向表in_num中插入记录,与之前不同的是,此时插入时不生成num_id,直接插入
insert into in_num values (80,105);
可以看到 last_insert_id() 仍旧是3

接下来一次插入两条
insert into in_num(num_val) values (1000),(10000);
select last_insert_id();
可以看到并不是82,而是81

其他注意事项
• If a stored procedure executes statements that change the value of LAST_INSERT_ID(), the changed value is seen by statements that follow the procedure call.
• For stored functions and triggers that change the value, the value is restored when the function or
trigger ends, so following statements will not see a changed value.
本文详细介绍了MySQL中last_insert_id()函数的使用方法及注意事项。通过实例演示了如何获取最后一次插入操作生成的自增ID值,包括在存储过程、函数和触发器中的表现。

2391

被折叠的 条评论
为什么被折叠?



