栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

递增字段时如何确保MySQL数据库中没有竞争条件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

递增字段时如何确保MySQL数据库中没有竞争条件?

这是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行,则其他人在此同时更新了该表。您必须重新开始-也就是说,选择新值,执行应用程序逻辑,然后再次尝试更新。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416394.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号