如何处理“或” ERD(表)设计中的关系? [英] How to handle an "OR" relationship in an ERD (table) design?

查看:195
本文介绍了如何处理“或” ERD(表)设计中的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个个人项目设计一个小数据库,其中一个表称为表 C ,需要有一个外键到两个表之一,请将它们称为 A B 。实现这一点的最好方法是什么?

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?

目前为止的想法:


  • 创建该表具有两个可空的外键字段连接到两个表。


    • 可能有一个触发器来拒绝插入和更新,导致0或2个为null。


    • 这打破了有关复制数据的规则。

    解决这个问题的更优雅的方法是什么?

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

    推荐答案

    您正在描述一种称为多形体协会的设计。这通常会让人陷入麻烦。

    You're describing a design called Polymorphic Associations. This often gets people into trouble.

    我通常推荐的:

    A  -->  D  <--  B
            ^
            |
            C
    

    在此设计中,您创建一个公共父表 D A B 参考。这类似于OO设计中的常见超类型。现在,您的子表 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.

    通过约束和复合键,您可以确保 D 中的给定行只能由 A B 但不能同时使用。

    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.

    这篇关于如何处理“或” ERD(表)设计中的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆