You're duplicating functionality by storing 'likes' in two places.
I didn't look at your weak entity (table for users and votes) so let's assume it will have three fields: user_id
, item_id
and vote TINYINT
. Primary key on user_id
and item_id
so the same user can only have one vote per item.
Set vote to 1 or -1 depending on up or down, instead of storing likes
in the item table, calculate total vote for an item dynamically like this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ?;
If you only want positive votes, do this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ? AND vote = 1;
When the user wants to record or change his vote, you can use REPLACE INTO
syntax (thanks to Anigel for the suggestion -- I totally missed it) in order to store the user's new vote:
REPLACE INTO user_votes (user_id, item_id, vote) VALUES (?, ?, ?);