DB Design for Choosing One of Multiple Possible Foreign Tables

后端 未结 2 406
粉色の甜心
粉色の甜心 2021-01-21 23:08

Say if I have two or more vastly different objects that are each represented by a table in the DB. Call these Article, Book, and so on. Now say I want to add a commentening feat

2条回答
  •  情歌与酒
    2021-01-21 23:25

    There is one other strategy: inherit1 different kinds of "commentable" objects from one common table then connect comments to that table:

    enter image description here

    All 3 strategies are valid and have their pros and cons:

    1. Separate comment tables are clean but require repetition in DML and possibly client code. Also, it's impossible to enforce a common key on them, unless you employ some form of inheritance, which begs the question: why not go straight for (3) in the first place?
    2. One comment table with multiple FKs will have a lot of NULLs (which may or may not be a problem storage and cache-wise) and requires adding a new column to the comments table whenever a new kind of "commentable" object is added to the database. BTW, you don't necessarily need the comment_type - it can be inferred from what field is non-NULL.
    3. Inheritance is not directly supported by current relational DBMSes, which brings its own set of engineering tradeoffs. On the up side, it could enable easy addition of new kinds of commentable objects without changing the rest of the model.

    1 Aka. category, subclassing, generalization hierarchy... For more on inheritance, take a look at "Subtype Relationships" section of ERwin Methods Guide.

提交回复
热议问题