mercredi 22 juin 2016

two transactions after commit/rollback will show different LAST_INSERT_ID()

Barebones simplicity. I have a single database and a single table:

create database testGrounds;
use testGrounds;
create table test1(
    id int primary key auto_increment,
    someData varchar(255)
);

Then i launch two sessions: one from command line (A), other from MySQL Workbench (B).

In session B i explicitly start a transaction, insert something test1, then roll it back. After rollback select LAST_INSERT_ID(); will show 1, but on session A - will show 0.

If you play different scenarios, like for instance with two concurrent transactions from both sessions, you can end up no only with different LAST_INSERT_ID() in A and B, but also it won't show the actual last inserted id (the id attribute in the test1 table). Odd.

Then, when i drop the entire database, select LAST_INSERT_ID(); will show its last number - whatever it is, it's not reset/erased.

My understanding of select LAST_INSERT_ID(); is that it is crucial when inserting data across multiple tables that has lots of foreign key relations. Should it be specific for each table and be reliable?

How else can i reliably insert data with FK relationships? Can't use the WHERE clause to find it, because, for example, in a table of names 'Tom Cruise' will not be unique...

Can someone explain?

Aucun commentaire:

Enregistrer un commentaire