"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to efficiently insert data into multiple MySQL tables in one transaction?

How to efficiently insert data into multiple MySQL tables in one transaction?

Posted on 2025-06-14
Browse:461

How to Efficiently Insert Data into Multiple MySQL Tables in a Single Transaction?

MySQL Insert into Multiple Tables

Attempting to insert data into multiple tables with a single MySQL query may yield unexpected results. While it may seem like multiple queries would resolve the issue, correlating the auto-increment ID from the user table to the manual user ID for the profile table presents a challenge.

Using Transactions and LAST_INSERT_ID()

To insert into multiple tables in a single transaction, use the following approach:

BEGIN;
INSERT INTO users (username, password) VALUES('test', 'test');
INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com');
COMMIT;
  • Begin a transaction with "BEGIN;".
  • Insert into the first table, capturing the auto-increment ID using "LAST_INSERT_ID()".
  • Insert into the second table, referencing the captured ID as "userid".
  • Commit the transaction with "COMMIT;".

Storing the Auto-Increment ID in a Variable

Alternatively, storing the auto-increment ID in a variable allows for referencing it in subsequent queries. This can be achieved using:

  • MySQL variable:

    INSERT INTO ...
    SELECT LAST_INSERT_ID() INTO @mysql_variable_here;
    INSERT INTO table2 (@mysql_variable_here, ...);
  • PHP variable:

    INSERT ...
    $result = mysql_query("SELECT LAST_INSERT_ID()");
    $id = mysql_result($result, 0);
    INSERT INTO table2 ($id, ...);

Transaction Considerations

Regardless of the approach chosen, consider the potential impact of interrupted execution. In the absence of transactions, inconsistency may arise in your database. To prevent this, wrap the insert statements in a transaction, as demonstrated above.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3