ReadUncommitted是否可以知道将存在的所有LOWER自动增量ID?
假设我们有一个带有自动递增主键的表.我要加载的所有ID都比我看到的最后一个ID大.
Suppose we have a table with an auto-increment primary key. I want to load all IDs greater than the last ID I have seen.
SELECT id
FROM mytable
WHERE id > 10;
采用幼稚的方法,我可能会跳过ID:
With the naive approach, I risk skipping IDs:
- 交易1声明ID为11.
- 交易2声明ID为12.
- 事务2提交.
- 我读取了所有ID> 10.我看到12,下次我将读取所有ID> 12.我跳过了11.
- 事务1提交.出于所有意图和目的,ID 11现在存在.
作为一种解决方案,我建议进行仔细检查以确保不会提交任何中间ID:
As a solution, I propose to do a double check to ensure that no intermediate IDs are about to be committed:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT COUNT(*)
FROM mytable
WHERE id > 10
AND id <= 12; -- Where 12 was the max seen in the first query
如果计数大于在第一个查询中看到的ID数量,则肯定有可能在该序列的空缺中提交其他ID.
If the count is greater than the number of IDs seen in the first query, then it is definitely possible that additional IDs will be committed in the gaps in that sequence.
问题是:反向是否成立?如果计数等于(或小于)在第一次查询中看到的ID数量,是否保证之间没有值?还是我错过了一些可能的情况,在这些情况下,有人要求提供ID,但是READ UNCOMMITTED
查询还没有看到它们?
The question is: does the reverse hold true? If the count is equal to (or less than) the number of IDs seen in the first query, is it guaranteed that there will be no values in between? Or am I missing some possible scenario where the IDs are being claimed, yet the READ UNCOMMITTED
query does not see them yet?
对于这个问题,请忽略:
For this question, please disregard:
- 手动插入ID.
- 倒退自动递增计数器.
Mysql在auto_increment期间锁定了表.
Mysql locks the table during auto_increment.
请参见
https://dev.mysql .com/doc/refman/5.7/en/innodb-auto-increment-handling.html
因此,如果版本中没有错误,通常不会发生此问题.
So that normally that problem doesn't occur, if there is no bug in the Version.
该锁的工作方式类似于信号量/关键部分.
The lock works like a semaphore/critical Section.