DB Design for Choosing One of Multiple Possible Foreign Tables

后端 未结 2 405
粉色の甜心
粉色の甜心 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:14

    I personally think your first option is best, but I'll throw this option in for style points:

    Comments have a natural structure to them. You have a first comment, maybe comments about a comment. It's a tree of comments really.

    What if you added one field to each object that points to the root of the comment tree. Then you can say, "Retrieve the comment tree for article 123.", and you could take the root and then construct the tree based off the one comment table.

    Note: I still like option 1 best. =)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题