Which system would be the best to go ahead with for voting function and why? ;
Putting the votes separately inside a database table and calculating the average when it is needed
Having only one row for one product. When a new vote comes, getting that vote form database, calculate it again and update the record. for example, we have a vote record for product 1. Its vote is totally 326 inside database and 45 people have voted. then we receive a new vote which is 4 and 开发者_高级运维for product 1. We take the record from database and then do the following function;
(326 + 4) / (45 + 1)
then save it to database again with total value of 330 and 46 as voted people.
I always go ahead with the first option but I wanna know what others are doing.
Well, it always depends on what you want to with the additional information about the votes.
If you want to know for example trends in voting (is the average going up or down) or you want to know it the votes are relatively old / new or what user has casted the vote (the 1-vote-per-person-check) etc. etc. etc. you want to store each vote in a separate table.
If all you care about is the end result the second option is way more efficient.
If you want to suppress that people can vote twice you will need the 1-row-per-vote
approach anyway, so I recommend the first option.
The second option might be better performance-wise - but should that ever be a problem, it's easy to use a caching-mechanism.
There are lots of factors to consider. Are you needing to defend against someone attacking your application server and modifying the vote count? Are you concerned with people's votes being discoverable? Are you concerned about locking-related performance issues? All of those will affect the decision, and the answers to those vary wildly depending on the specific scenario.
精彩评论