3

Let's assume we have application with pages, posts and events. With each part of this application we want to have comments. Now let's take a look into tables for our DB.

1. One comment table, object and object_id as foreign key

Page/Post/Event has many comments, foreign key object, object_id

comments table
+-------------+-------------+-------------+-------------+
| id          | object      | object_id   | text        |
=========================================================
| 1           | Page        | 1           | Comment 1   |
+-------------+-------------+-------------+-------------+
| 2           | Post        | 1           | Comment 2   |
+-------------+-------------+-------------+-------------+
| 3           | Event       | 1           | Comment 3   |
+-------------+-------------+-------------+-------------+

2. Multiple comments tables

Page (Post, Event) has many page comments, foreign key page_id

page_comments table
+-------------+-------------+-------------+
| id          | page_id     | text        |
===========================================
| 1           | 1           | Comment 1   |
+-------------+-------------+-------------+

post_comments table
+-------------+-------------+-------------+
| id          | post_id     | text        |
===========================================
| 1           | 1           | Comment 2   |
+-------------+-------------+-------------+

event_comments table
+-------------+-------------+-------------+
| id          | event_id    | text        |
===========================================
| 1           | 1           | Comment 3   |
+-------------+-------------+-------------+

I have used specific example, but this can apply to any other 1:N tables or even with M:N (tags), but for simple showcase, this should be good.

We should discuss

  • Performance concerns
  • Design pros and cons

Initial thoughts

  • case 1 means less tables in DB, easier to read, reusable application code
  • case 1 is better when doing query on all comments (would have to use union at case 2)
  • case 2 is better in regards of normalization (3NF)
  • case 2 is easier to backup (dump) parts of the system, e.g. pages itself with their comments
  • case 2 should be better with performance because less rows => faster
Luboš Remplík
  • 526
  • 5
  • 10
  • It strikes me that case 2 is easier to update when the data changes. If that's true, it's directly connected to differences in normalization. Theory is practical. – Walter Mitty Jul 26 '17 at 11:29
  • @WalterMitty thanks for the answer – Luboš Remplík Jul 27 '17 at 07:08
  • Similar / same questions at SO, https://stackoverflow.com/questions/9021838/database-design-multiple-tables-vs-a-single-table https://stackoverflow.com/questions/9774715/mysql-multiple-tables-or-one-table-with-many-columns – Luboš Remplík Jul 27 '17 at 07:08

0 Answers0