anfrasa
anfrasa

Reputation: 65

how to handle multiple inserts at once

I need to run multiple queries at once. Below you can see an example. How can I be sure that after I make an insert on table A and I store last insert id on a variable, it will be the right value inserted on the other tables if another insert occurs at the same time? Do I have to lock all tables, run my queries and then unlock 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);

Upvotes: 4

Views: 694

Answers (3)

Marc Audet
Marc Audet

Reputation: 46825

If I were doing this, I would probably open a transaction as referenced http://dev.mysql.com/doc/refman/5.0/en/commit.html

If you were using a framework like CodeIgniter, you would have access to a database abstraction layer that would work in a similar fashion, for example, http://codeigniter.com/user_guide/database/transactions.html

Upvotes: 1

Suroot
Suroot

Reputation: 4423

Per the MySQL documentation last_insert_id() only applies to the current session.

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

Upvotes: 1

RichardTheKiwi
RichardTheKiwi

Reputation: 107816

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);

The variable @last_id is global, but unique to your specific session. Therefore, once it is set, the value doesn't change unless you change it again.

As for last_insert_id(), specifically the manual states

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

So it does not matter what other connections do. The inserts into b and c are guaranteed to use the id generated for a.

Upvotes: 2

Related Questions