这是3种不同的方法:
原子更新
update table set tries=tries+1 where condition=value;
这将是原子完成的。
使用交易
如果确实需要首先选择该值并在应用程序中对其进行更新,则可能需要使用事务。这意味着您必须使用InnoDB,而不是MyISAM表。您的查询将类似于:
BEGIN; //or any method in the API you use that starts a transactionselect tries from table where condition=value for update;.. do application logic to add to `tries`update table set tries=newvalue where condition=value;END;
如果事务失败,则可能需要手动重试。
版本方案
一种常见的方法是在表中引入版本列。您的查询将执行以下操作:
select tries,version from table where condition=value;.. do application logic, and remember the old version value.update table set tries=newvalue,version=version + 1 where condition=value and version=oldversion;
如果该更新失败/返回受影响的0行,则其他人在此同时更新了该表。您必须重新开始-也就是说,选择新值,执行应用程序逻辑,然后再次尝试更新。



