php mysql 查询多个id_php – MySQL如何同时管理来自多个用户的多个查询?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值