I’m trying to make a reddit-like web application from scratch.
I’m not sure how to store the up and down votes.
I’m thinking about creating a table called ‘user_votes’
with fields ‘id’, ‘user_id’, ‘voted_link_id’, ‘up_or_down’
So it’s basically adding a row for “who voted what on what” every time a user votes.
I’m inserting a new row instead of just adding 1, because the user profile page will have to show the list of links the user voted. So I need to keep track of every single votes. But I don’t feel like it’s efficient.
I’m not familiar with web applications heavily relying on DB.
Please guide me.
P.S.
Which columns should be indexed?
Actually you want both.
You must have the table with Article_ID, User_ID, +1 or -1. This is for exactly the reasons you’ve stated. You’ll need to show a user’s votes as a running account. You’ll also us that to ensure uniqueness.
You now have to think about frequency. Articles will be viewed more frequently than voted on. Because of that, you’d have to do a lot of SUMs on the Vote table that result in the exact same values being produced.
Instead you should keep two counters on the Article table: a total of upvotes and a total of downvotes. The reason for two is that, the sum is inconsequential since the two values are on the same row. Second you may want to implement something that will expose those values like SO does. (You can’t see that until you get so many points (about 1500)).
You may want to show a list of articles and the total points each has… you don’t want to SUM over the votes table for a long list of articles. You also may want to allow people to set limits on articles, “only show me over +10”. Again, you don’t want to sum over the votes table every time someone opens their home page.