How to insert data to multiple tables with foreign key dependencies involved (MySQL)

前端 未结 1 562
一个人的身影
一个人的身影 2021-02-09 16:22

I am looking for the best-practice way to insert data to multiple MySQL tables where some columns are foreign key dependencies. Here is an example:

Table: contac         


        
1条回答
  •  长发绾君心
    2021-02-09 17:02

    In short, you want to use transactions (more doc on this) so that your inserts are atomic. This is the only way to guarantee that all (or none) of your data will be inserted. Otherwise, you can get into the situation you describe where the database becomes unavailable after some insertions and others are unable to complete. A transaction tells the database that what you are doing is all-or-nothing and so it should roll back if something goes wrong.

    When you are using synthetic primary keys, as you are, PHP and other languages provide mechanisms for getting the last inserted id. If you want to do it entirely in MySQL you can use the LAST_INSERT_ID() function. You will end up with code like this:

    START TRANSACTION;
    INSERT INTO foo (auto,text)
        VALUES(NULL,'text');         # generate ID by inserting NULL
    INSERT INTO foo2 (id,text)
        VALUES(LAST_INSERT_ID(),'text');  # use ID in second table
    COMMIT;
    

    0 讨论(0)
提交回复
热议问题