Skip to content Skip to sidebar Skip to footer

Multiple Inserted Row Ids

I am inserting multiple rows at once like: INSERT INTO person VALUES ('joe', 50), ('jon', 24); I then need to use their id to link the above to another table. Normally I would do

Solution 1:

Insert the values using single statements and wrap them into a transaction, e.g:

START TRANSACTION;
INSERTINTO person  VALUES ('joe', 50);
INSERTINTO hobbies VALUES (LAST_INSERT_ID(),'golf');
COMMIT;

You may take a slight performance hit but this should give you consistent results. Incrementing the value returned by LAST_INSERT_ID() is not safe as there may have been concurrent inserts that modified the AUTO INCREMENT value.

Post a Comment for "Multiple Inserted Row Ids"