gpt4 book ai didi

Mysql事务同时发生

转载 作者:行者123 更新时间:2023-11-29 17:24:05 24 4
gpt4 key购买 nike

两个交易可以同时发生吗?假设您有事务 A 和 B,每个事务都会执行读取操作以获取某列的最大值,然后执行写入操作以插入具有该 max+1 的新行。是否有可能 A 执行读取以获得最大值,然后 B 在 A 写入之前执行读取,导致两个事务向该列写入相同的值?

将隔离级别设置为读取未提交为 false 来执行此操作似乎可以防止重复,但我无法理解为什么。

最佳答案

Can two transactions occur at the same time?

是的,这是很有可能的,事实上,所有 RDBMS 都需要支持该功能以加快速度。想象一下一个由数千名用户同时访问的应用程序,如果一切按顺序进行,用户可能需要等待一天才能获得响应。

Let's say you have transactions A and B, each of which will perform a read to get the max value of some column then a write to insert a new row with that max+1. Is it possible that A performs a read to get the max, then B performs a read before A writes, causing both transactions to write the same value to the column?

如果 A 和 B 发生在两个不同的 session 中,则这是很可能的用户情况。

Doing this with isolation level set to read uncommitted to false seems to prevent duplicates, but I can't wrap my head around why?

我认为,您对使用隔离 block 获取下一个增量号的要求很常见,这里您需要指示数据库执行互斥的读取操作以进行写入操作,您可以通过设置隔离来指示数据库执行此操作,或者可能是“临时隔离”级别应该可以解决您的问题。

如果获取下一个数字只是问题,并且没有其他限制,那么

My Sql AUTO_INCRMENT 将是最适合您的答案。但看来,你特意问了这个问题,说明,你可能有所拘束。

引用我的类似问题和answer .

您的解决方案应如下所示。

begin;
select last_number from TABLE1 ... FOR UPDATE;

Read the result in App.

update TABLE1 set last_number=last_number+1 where ...;
commit;

关于Mysql事务同时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51070779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com