只是举个例子:
我有一个管理用户投票的PHP脚本.
当用户投票时,脚本会进行查询以检查某人是否已经投票选择了相同的ID /产品.如果没有人投票,则它进行另一个查询并将ID插入一般ID投票表,另一个将数据插入每用户ID投票表.而这种行为在其他类型的脚本中重复出现.
问题是,如果两个不同的用户同时投票,那么代码的两个实例可能会尝试插入一个新的ID(或某些类似的查询),这会产生错误?
如果是,我如何防止这种情况发生?
谢谢?
重要提示:我正在使用MyISAM!我的网站托管不允许InnoDB.
问题是,如果两个不同的用户同时投票,那么代码的两个实例可能会尝试插入一个新的ID(或某些类似的查询),这将给出一个错误
是的,您最终可能会进行两次插入查询.根据表上的约束,其中一个将生成错误,或者您将在数据库中最终得到两行.
我相信,你可以通过应用一些锁定来解决这个问题.例如,如果您需要为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;
Run Code Online (Sandbox Code Playgroud)
这里有更多信息
MySQL还提供了另一种解决方案,可能适用于此处,重复插入
例如,你可能只能这样做:
insert into votes(numberOfVotes,productId) values(1,theProductId ) on duplicate key
update numberOfVotes = numberOfVotes + 1;
Run Code Online (Sandbox Code Playgroud)
如果您的投票表在产品ID列上有唯一键,则如果特定的theProductId不存在,则上面将执行插入,否则它将执行更新,其中numberOfVotes列增加1
如果在将产品添加到数据库的同时在投票表中创建了一行,则可以避免大量此操作.这样你就可以确定你的产品总是有一排,只需在那一行发出UPDATE.
| 归档时间: |
|
| 查看次数: |
9402 次 |
| 最近记录: |