mySQL - Insert into three tables

前端 未结 3 1474
逝去的感伤
逝去的感伤 2020-12-11 10:44

I recently asked this question.

I have a relational database with three tables. The first containts id\'s that r

相关标签:
3条回答
  • 2020-12-11 10:59

    You always use transactions when performing multiple updates. If one update fails you will want to roll back previous successful updates so you don't violate any unenforced constraints of the relational model.

    0 讨论(0)
  • 2020-12-11 11:03

    You can't insert into multiple tables with one query, You'll have to break it up to multiple queries.

    0 讨论(0)
  • 2020-12-11 11:09

    You should definitely do the three inserts in a transaction. I would probably write a stored procedure to handle the inserts.

    EDIT:

    Here is an example of a stored procedure with a transaction. Note the use of LAST_INSERT_ID() to get the ID of the previously inserted record. This is only two tables, but you should be able to extend it to three tables.

    DELIMITER //
    CREATE PROCEDURE new_engineer_with_task(
      first CHAR(35), last CHAR(35), email CHAR(255), tool_id INT)
    BEGIN
    START TRANSACTION;
       INSERT INTO engineers (firstname, lastname, email) 
         VALUES(first, last, email);
    
       INSERT INTO tasks (engineer_id, tool_id) 
         VALUES(LAST_INSERT_ID(), tool_id);
    COMMIT;
    END//
    DELIMITER ;
    

    And you call it like so:

    CALL new_engineer_with_task('Jerry', 'Fernholz', 'me@somewhere.com', 1);
    
    0 讨论(0)
提交回复
热议问题