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

后端 未结 2 1846
心在旅途
心在旅途 2021-01-18 17:45

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

2条回答
  •  长发绾君心
    2021-01-18 18:17

    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.

提交回复
热议问题