开发者

Database design: should I use a mapping table?

开发者 https://www.devze.com 2023-01-29 03:53 出处:网络
Using a question and answer site like this as an example.Say I have question, answer, and comment tables.Questions and answers can each have multiple comments.

Using a question and answer site like this as an example. Say I have question, answer, and comment tables. Questions and answers can each have multiple comments.

Would it be开发者_开发知识库 best to:

  1. create QuestionComment, and AnswerCommenttables to map from questions/answers to comments (each containing the question/answer pk and comment pk)?

  2. Or should I only have the comment table containing 2 nullable foreign keys to question and answer (one of which will always be null since a comment can apply only to a single "item")?

It seems like (1) maintains referential integrity while (2) is more compact. Is one preferred over the other? Should mapping tables be reserved only for many-to-many relationships?


Will you use both comments in the same way? If so, then (2) otherwise (1)

If you use (1), you can create a view over both tables to make them appear as one.

In case (2), you can add a Trigger to enforce there being only one Foreign Key column being populated per row, or as @Ronnis suggested using a CHECK constraint (a better technique).


I've seen either approach done in practice, but I prefer (1) a little more:

I think (1) expresses your domain a little more clearly to someone browsing the schema - they'll see Answer and AnswerComment right next to each other. If answer comments and question comments are in the same table you have to drill down into the comment table to see to which object a comment can belong.

If you're using a domain model with separation between domain objects and persistence, the question is moot: it doesn't matter whether you store them in the same table or different tables. (And they would be separate classes only if they behave differently.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号