我正试图为像SO这样的投票系统提出一个很好的优雅解决方案。如果有一种方法可以使用触发器实现优雅,我无法弄明白,所以我正在尝试使用存储过程。这就是我想出来的,它并不是那么我要求的想法。我甚至可能有一个查询而不是查询+存储过程。但我真的很想知道更新用户积分和插入/更新投票的简洁方法。积分在一个单独的表中,以便按程序更新。
给予好评
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
翻转(当用户从上到下更改投票时)
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
答案 0 :(得分:0)
我个人认为您的案例中不需要存储过程。如果您正在跟踪用户投票,则表示您可以使用用户ID。我建议打开一个mysql事务,在投票表中执行插入,然后执行更新以跟踪用户的分数。然后,如果两个调用都成功提交事务,这将确保数据完整性。
也许您可以分享您想要使用程序的具体原因?
答案 1 :(得分:0)
我假设votes
表有3列(post_id,user_id,weight)。您可以使用以下查询:
insert into votes(post_id, user_id, weight)
values(post_id_in, user_id_in, weight_in)
on duplicate key update
set
weight = weight_in;
使用时应具有唯一索引(post_id,user_id)。
如果您对数据进行非规范化处理,则表格posts
包含您需要重新计算的总票数列。