如何处理“OR”问题ERD(表)设计中的关系?

发布于 2024-08-18 02:45:42 字数 326 浏览 4 评论 0原文

我正在为个人项目设计一个小型数据库,其中一个表(称为表C)需要有两个表之一的外键(称为A) code> 和 B,因条目而异。实现这一点的最佳方法是什么?

到目前为止的想法:

  • 创建一个表,其中两个可空外键字段连接到两个表。
    • 可能有一个触发器来拒绝插入和更新,这会导致其中 0 或 2 个为空。
  • 两个具有相同数据的独立表
    • 这违反了重复数据的规则。

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里兽 2024-08-25 02:45:42

您正在描述一种称为多态关联的设计。这常常会给人们带来麻烦。

我通常建议:

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

在此设计中,您创建一个公共父表 DAB 都引用它。这类似于面向对象设计中的常见超类型。现在,您的子表 C 可以引用超级表,然后您可以从那里访问相应的子表。

通过约束和复合键,您可以确保 D 中的给定行只能由 AB 引用,但不能同时被两者引用。

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.

落花浅忆 2024-08-25 02:45:42

如果您确定 C 将仅引用两个表中的一个(而不是 N 个表中的一个),那么您的第一选择是一种明智的方法(也是我之前使用过的方法) 。但是,如果您认为外键列的数量将继续增加,这表明存在一些可以合并的相似性或重叠,您可能需要重新考虑。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文