mysql插入竞争条件

mysql插入竞争条件

本文介绍了mysql插入竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在MySQL中停止竞争条件?眼前的问题是由一个简单的算法引起的:

How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:

  1. 从表中选择一行
  2. 如果不存在,请插入

,然后您得到重复的行,或者如果您通过唯一/主键阻止它,则会出现错误.

and then either you get a duplicate row, or if you prevent it via unique/primary keys, an error.

现在通常我认为事务在这里有用,但是因为该行不存在,所以事务实际上并没有帮助(或者我遗漏了什么?).

Now normally I'd think transactions help here, but because the row doesn't exist, the transaction don't actually help (or am I missing something?).

LOCK TABLE听起来有些矫kill过正,尤其是如果该表每秒更新多次.

LOCK TABLE sounds like an overkill, especially if the table is updated multiple times per second.

我能想到的唯一其他解决方案是对每个不同的id使用GET_LOCK(),但是没有更好的方法吗?这里也没有可伸缩性问题吗?而且,对每个表执行此操作听起来有点不自然,因为这对我而言在高并发数据库中听起来是一个非常普遍的问题.

The only other solution I can think of is GET_LOCK() for every different id, but isn't there a better way? Are there no scalability issues here as well? And also, doing it for every table sounds a bit unnatural, as it sounds like a very common problem in high-concurrency databases to me.

推荐答案

您想要的是锁定表

或者如果看起来过分的话插入IGNORE 与检查该行是否已实际插入.

or if that seems excessive how about INSERT IGNORE with a check that the row was actually inserted.

这篇关于mysql插入竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:18