简体   繁体   中英

What would be the best table structure for user post sharing system?

I am creating an app where users can create content, other users can like, comment those posts, now I want to implement sharing feature. I want to know what would the best way to implement this. Following is the table structure for posts

| post_id | post_content | post_user | post_date |

Users can see post only from people they are following.

First of all I thought I would add another row to the above posts table but that would create unnecessary duplication of data, then I thought of adding rows to my user_action table in which I am storing post likes and comments, but thats making the system complicated..

I searched over SO, but couldn't find anything, or may be my search terms were not reachable to those questions.

Is there any better way for achieving this?

I agree that adding another row with duplicated data is not good. Let's take a closer look at what you're trying to do.

You have users, and you have posts. These should definitely be separate entities with their own table.

'Like' is a NM relationship since a user can like any number of posts, and a post can be liked by any number of users. So this will be its own table with two foreign keys, user and post.

Comments are similar to posts, but contains some contents. The same user and post combination can also contain multiple comments. Comments will also be its own table with two foreign keys, user and post. The combination of these two will be unique in like, but non-unique in comment.

Now the sharing part. You want users to be able to follow other users. This is also an NM relationship since any user can follow any number of users, and any user can be followed by any number of users. Thus, you'll want one more table for this relationship with two foreign keys, user and user. The combination of these two user keys will be unique.

For a given user John, to find all posts of users that he's following, we can use the following pseudo query:

select posts.*
from posts
join user intermediateUser on posts.author = intermediateUser.id
join follow on follow.followee = intermediateUser.id
where follow.follower = John

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM