I'm designing a small database for a personal project, and one of the tables, call it table C
, needs to have a foreign key to one of two tables, call them A
and B
, differing by entry. What's the best way to implement this?
Ideas so far:
What's a more elegant way of solving this problem?
There can be more than one relationships between two entities. Your first linking table is not required. The DepartmentID in DepartmentEmploys can simply be a FK in the Employee table. Also, the second linking table is acceptable only if a Department can have multiple Employee as managers.
Cardinality and Ordinality The relationship, in this case, follows a “one to many” model. There are a number of notations used to present cardinality in ER diagrams. Chen, UML, Crow's foot, Bachman are some of the popular notations. Creately supports Chen, UML and Crow's foot notations.
The key to resolve m:n relationships is to separate the two entities and create two one-to-many (1:n) relationships between them with a third intersect entity. The intersect entity usually contains attributes from both connecting entities. To resolve a m:n relationship, analyze your business rules again.
You're describing a design called Polymorphic Associations. This often gets people into trouble.
What I usually recommend:
A --> D <-- B
^
|
C
In this design, you create a common parent table D
that both A
and B
reference. This is analogous to a common supertype in OO design. Now your child table C
can reference the super-table and from there you can get to the respective sub-table.
Through constraints and compound keys you can make sure a given row in D
can be referenced only by A
or B
but not both.
If you're sure that C
will only ever be referring to one of two tables (and not one of N), then your first choice is a sensible approach (and is one I've used before). But if you think the number of foreign key columns is going to keep increasing, this suggests there's some similarity or overlap that could be incorporated, and you might want to reconsider.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With