I'm working on a rating system in PHP and MYSQL with votes up and votes down.
I have a database called votes
which contains all the votes done by registered users (1 for up vote and -1 for a down vote)
For every post that can rated there is a recap of all the up votes, down votes and also the net vote (up minus down votes).
When someone up votes a post there is a INSERT ... ON DUPLICATE KEY UPDATE
query that inserts or updates the table which contains all the votes.
I then update the posts row with the new number of up votes, down votes and also the new net votes.
My problem is that I need to know if the first query was an insert or a update because if it is an update I will need to subtract the old vote and add the new one but id it is just an insert I don't need to subtract anything and just increment the vote.
I'd suggest that you do not optimize voting calculating prematurely, and after each new vote for some post you just recalculate all the votes for this post, regardless of whether that was INSERT
or UPDATE
that triggered recalculation. Then store the result to DB.
Moreover, it is simpler throw out even total votes caching and calculate these on the fly, whenever you need.
Only when you face performance problems, you should measure your expenses and check, what is the bottleneck. Odds are that the voting calculation should be not the first thing to optimize in your application.
Keep your life simpler.