How to handle multiple inserts at once

I need to run several queries at once. Below you can see an example. How can I be sure that after I make an insert in table A and I save the last insert identifier for the variable, it will be the correct value inserted into other tables if another insert occurs at the same time? Do I need to lock all tables, run my queries, and then unlock the tables? I read something about transactions. Do I need them? Thanks for any advice.

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);
+3
source share
3 answers

In this sequence

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 , . , , .

last_insert_id(), manual

, , .

, , . b c , a.

+2

MySQL documentation last_insert_id() .

, , . , , AUTO_INCREMENT, , AUTO_INCREMENT . , AUTO_INCREMENT. , , .

+1

All Articles