What is the best way to insert rows into tables with references 1 to 1 of each other?
I mean, in a MySQL 5.5 and tables InnoDB, I have a database design similar to the following

The problem arises when we try to insert rows in table1 and table2. Since there is no multi-table insert in MySQL, I can not insert a row becouse the foreign keys are NOT NULL fields in both tables and should be inserted simultaneously in both.
Which is the bes way to solve this problem?
I have in mind 3 possible solutions, but I want to know if there are more than these or which is the best and why.
-
Set the foreign key field as NULLABLE and after insert one row in a table, insert the other one and afterwards, update de first one.
-
Just as indicated above but with an special value like -1. First, insert in one table with foreign
key = -1that is equivalent to NULL but avoiding set the field as NULLABLE. Afterwards, we insert the row in the other table and update the first one inserted. -
Create a relational table between both though it is not really necessary because it is a 1 to 1 ratio
Thanks!!
EDIT
I briefly explain what I need this circular relationship: It is a denormalization from the parent table to one of its childs. It is made in order of high performance to have always the reference of the best ranked child from a parent table.
I’ll make this an answer as I feel this is a design flaw.
First, if the two tables are in true
1:1relationship, why don’t you just have one table?Second, if it’s not a true
1:1relationship but a supertype-subtype problem, you don’t need this circular foreign keys either. Lets saytable1isEmployeeandtable2isCustomer. Off course most customers are not employees (and vice-versa). But sometimes a customer may be an employee too. This can be solved having 3 tables:In the scenario you describe you have two tables
ParentandChildhaving1:Nrelationship. Then, you want to store somehow the best performing (based on a defined calculation) child for every parent.Would this work?:
This way, you enforce the wanted referential integrity (every BestChild is a Child, every Parent has only one BestChild) and there is no circular path in the References. The reference to the best child is stored in the extra table and not in the
Parenttable.You can find BestChild for every Parent by joining:
Additionally, if you want to store best children for multiple performance tests (for different types of tests, or tests in various dates), you can add a
testfield, and alter the Primary Key to(test, parentid):