Justin Kruskie
Justin Kruskie

Reputation: 422

Storing Posts&Comments in seperate tables or together

I was wondering what would be best, storing my comments in my post table or them having their own table?

My posts table only has an id, userid, image url and description of the post. I join the posts table with my users table to retrieve the name of the author.

Should I just add a new column to my posts table for comments and store a json of all the comments or should I create a new comments table and log either each comment as a separate row? I am not planning on adding fields to respond to people, just storing the comments. I'm assuming just adding another column would work fairly well.

If I stored the comments in the posts table then I wouldn't have to make a separate api call to gather them.

Thanks, would love to hear your ideas.

Upvotes: 0

Views: 295

Answers (2)

gmastro
gmastro

Reputation: 126

You could add an id_parent column next to your id having the very same properties excluding the AUTO_INCREMENT and a DEFAULT to 0.

The given column can point to already existing id from previous posts. In case that this is a new post it can remain to the default value.

This will work in case that you will not constrain the new column with FOREIGN KEYS. You can set an INDEX if you require to search for faster all posts with replies.

That would also give you the flexibility to quote posts over posts over posts without the need to create new tables and searching all over the place. It might lack in normalization but it will save you time and effort in complexity.

Upvotes: 1

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

If you use a relational database then right way is usage normalization and normal forms. It means you should create two separate tables: posts and post comments

Upvotes: 2

Related Questions