I will answer this question, because I believe that this is a design error.
First, if the two tables are in a true 1:1
ratio, why don't you have only one table?
Secondly, if this is not a true 1:1
relationship, but a supertype-subtype problem, you also do not need these circular foreign keys. Suppose table1
is Employee
and table2
is Customer
. Of course, most customers are not employees (and vice versa). But sometimes the client can be an employee. This can be solved by having 3 tables:
Person ------ id PRIMARY KEY: id Employee -------- personid lastname firstname ... other data PRIMARY KEY: personid FOREIGN KEY: personid REFERENCES Person(id) Customer -------- personid creditCardNumber ... other data PRIMARY KEY: personid FOREIGN KEY: personid REFERENCES Person(id)
In the scenario you are describing, there are two tables, Parent
and Child
, with a ratio of 1:N
Then you want to keep the child element for each parent as efficient as possible (based on a specific calculation).
Will this work ?:
Parent ------ id PRIMARY KEY: id Child ----- id parentid ... other data PRIMARY KEY: id FOREIGN KEY: parentid REFERENCES Parent(id) UNIQUE KEY: (id, parentid) --- needed for the FK below BestChild --------- parentid childid ... other data PRIMARY KEY: parentid FOREIGN KEY: (childid, parentid) REFERENCES Child(id, parentid)
Thus, you perform the required referential integrity (each BestChild is a child, each parent has only one BestChild), and the links do not have a round trip. The reference to the best child is stored in an additional table, not in the Parent
table.
You can find BestChild for each parent by joining it:
Parent JOIN BestChild ON Parent.id = BestChild.parentid JOIN Child ON BestChild.childid = Child.id
In addition, if you want to store the best children for several performance tests (for different types of tests or tests on different dates), you can add the test
field and change the primary key to (test, parentid)
:
BestChild --------- testid parentid childid ... other data PRIMARY KEY: (testid, parentid) FOREIGN KEY: (childid, parentid) REFERENCES Child(id, parentid) FOREIGN KEY: testid REFERENCES Test(id)