Mysql – How to create Parent record on Child record creation and assign Parent ID to Child record in MySQL

MySQL

I have 2 tables – [stakeholders] and [organizations].

FK from [organizations.stakeholder_id] to [stakeholders.id].

I want to create [stakeholder] record automatically when new [organization] is created AND to assign newly created [stakeholder.id] back to [organizations.stakeholder_id] in the same transaction.

Is it possible and how?

Best Answer

No it's not possible to create a child record without creating the parent record, but you can always(even in programming languages) insert into the parent table first and then insert into the child table.

insert into parent_table(id) values(1);
insert into child_table(childid,name,id) values(1,"x",1);

For example in any programming language if you have the id number that you want to add to your database you can use it in both insert statements.