gpt4 book ai didi

mysql - 如何一次处理多个插入

转载 作者:可可西里 更新时间:2023-11-01 08:08:00 25 4
gpt4 key购买 nike

我需要一次运行多个查询。下面你可以看到一个例子。我如何确定在表 A 上进行插入并将最后一个插入 ID 存储在变量上之后,如果同时发生另一个插入,它将是插入到其他表上的正确值?我是否必须锁定所有表、运行查询然后解锁表?我读了一些关于交易的东西。我需要它们吗?感谢您的任何建议。

create table a (
id int not null auto_increment primary key,
name varchar(10)
) engine = innodb;

create table b (
id int not null auto_increment primary key,
id_a int
) engine innodb;

create table c (
id int not null auto_increment primary key,
id_a int)
engine innodb;

insert into a (name) values ('something');
set @last_id = last_insert_id();
insert into b (id_a) values (@last_id);
insert into c (id_a) values (@last_id);

最佳答案

按照这个顺序

insert into a (name) values ('something');
set @last_id = last_insert_id();
insert into b (id_a) values (@last_id);
insert into c (id_a) values (@last_id);

变量 @last_id 是全局的,但对于您的特定 session 是唯一的。因此,一旦设置,该值就不会改变,除非您再次更改它。

至于 last_insert_id(),特别是 manual

The ID that was generated is maintained in the server on a per-connection basis.

所以其他连接做什么并不重要。 bc 的插入保证使用为 a 生成的 id。

关于mysql - 如何一次处理多个插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com