The question is, if two different users votes simultaneously its possible that the two instances of the
code try to insert a new ID (or some similar type of query) that will give an erro
是的,您最终可能会进行两次插入查询.根据表上的约束,其中一个将生成错误,或者您将在数据库中最终得到两行.
我相信,你可以通过应用一些锁定来解决这个问题.
例如如果您需要为ID为theProductId的产品添加投票:(伪代码)
START TRANSACTION;
//lock on the row for our product id (assumes the product really exists)
select 1 from products where id=theProductId for update;
//assume the vote exist, and increment the no.of votes
update votes set numberOfVotes = numberOfVotes + 1 where productId=theProductId ;
//if the last update didn't affect any rows, the row didn't exist
if(rowsAffected == 0)
insert into votes(numberOfVotes,productId) values(1,theProductId )
//insert the new vote in the per user votes
insert into user_votes(productId,userId) values(theProductId,theUserId);
COMMIT;
更多信息here
MySQL也提供了另一种解决方案,可能适用于此,insert on duplicate
例如你可能只能这样做:
insert into votes(numberOfVotes,productId) values(1,theProductId ) on duplicate key
update numberOfVotes = numberOfVotes + 1;
如果您的投票表在产品ID列上有唯一键,则上述内容将为
如果特定的theProductId不存在则执行插入,否则它将执行更新,其中numberOfVotes列增加1
如果在将产品添加到数据库的同时在投票表中创建了一行,则可以避免大量此操作.这样你就可以确定你的产品总是有一排,只需在那一行发出UPDATE.