Paste into two tables

Can I insert two tables at once? I need to insert some data into a table (contactinformation), and then based on the insertion of the primary key in userstable and have the primary key defined as a field (foreign key). Is it possible?

thank

+5
source share
3 answers

You can write a procedure for this.

DELIMITER //  

CREATE PROCEDURE `proc1` (contactinformation colums... usertable columns...)  
BEGIN  
    INSERT INTO contactinformation values(contactinformation colums ...);
    INSERT INTO usertable values(LAST_INSERT_ID(), contactinformation colums ...);
END//

DELIMITER ;  

contactinformation colums...means defining the columns of the contact data table.
usertable columns...means defining the columns of a usable table.

After the first insertion, you can get the insertion identifier if there is any automatic column in the contact information table. Then use this key in the second insert statement.

+2
source

, JOIN, .

+2

You can create a trigger on table1to insert the same values ​​into table2.

0
source

All Articles