MySQL之last_insert_id()

本文详细介绍了MySQL中last_insert_id()函数的使用方法及注意事项。通过实例演示了如何获取最后一次插入操作生成的自增ID值,包括在存储过程、函数和触发器中的表现。

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.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值