Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle an "OR" relationship in an ERD (table) design?

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:

  • Create the table with two nullable foreign key fields connecting to the two tables.
    • Possibly with a trigger to reject inserts and updates that would result 0 or 2 of them being null.
  • Two separate tables with identical data
    • This breaks the rule about duplicating data.

What's a more elegant way of solving this problem?

like image 957
C. Ross Avatar asked Jan 20 '10 01:01

C. Ross


People also ask

Can 2 relationships be related in an ER diagram?

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.

What are the two different types of relationships in an ER diagram?

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.

How do you resolve a one-to-many relationship?

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.


2 Answers

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.

like image 63
Bill Karwin Avatar answered Sep 23 '22 17:09

Bill Karwin


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.

like image 45
John Feminella Avatar answered Sep 22 '22 17:09

John Feminella