I’m trying to come up with a nice elegant solution for a voting system like SO’s. If there’s a way to do it with elegance using triggers I couldn’t figure it out so I’m trying with stored procedures. This is what I’ve come up with, It’s not pretty so I’m asking for ideas. I’ll probably even have one query rather than the query+stored procedure. But I’d really like to know a clean way to update a user’s points and insert/update votes. Points are in a separate table to be updated by procedure.
Upvote
INSERT INTO votes
ON DUPLICATE KEY
UPDATE votes
SET v.weight = v.weight + 1
WHERE v.weight = 0 OR v.weight = -1
AND v.userid = {$uid}
AND v.itemid = {$itemid}
//call procedure to +1 user points
Downvote
INSERT INTO votes
ON DUPLICATE KEY
UPDATE votes
SET v.weight = v.weight - 1
WHERE v.weight = 1 OR v.weight = 0
AND v.userid = {$uid}
AND v.itemid = {$itemid}
//call procedure to -1
Flipdown (when user changes vote from up to down)
INSERT INTO votes
ON DUPLICATE KEY
UPDATE votes
SET v.weight = -1
WHERE v.weight = 1
AND v.userid = {$uid}
AND v.itemid = {$itemid}
//call procedure to -2
Flipup
INSERT INTO votes
ON DUPLICATE KEY
UPDATE votes
SET v.weight = 0
WHERE v.weight = -1
AND v.userid = {$uid}
AND v.itemid = {$itemid}
//call procedure to +2
I assume that
votestable has 3 columns (post_id, user_id, weight). You can use the following query:Use should have unique index on(post_id, user_id).
If you denormalize data and table
postshas column for total votes that you need to recalculate it.