How many rows will be locked by SELECT … ORDER BY xxx LIMIT 1 FOR UPDATE?

后端 未结 4 1871
刺人心
刺人心 2020-12-04 18:14

I have a query with the following structure:

SELECT ..... WHERE status = \'QUEUED\' ORDER BY position ASC LIMIT 1 FOR UPDATE;

It\'s a singl

4条回答
  •  生来不讨喜
    2020-12-04 18:33

    I've made tests. Created the following table:

    id  data1   data2
    1   1   2
    2   2   1
    5   2   2
    6   3   3
    3   3   4
    4   4   3
    

    Then I created first connection with transaction:

    SELECT id FROM test ORDER BY data1 LIMIT 1 FOR UPDATE;
    

    result was the row with id=1;

    Then I created second transaction from another connection without commiting first:

    SELECT id FROM test WHERE data1=2 FOR UPDATE;
    

    It didn't block. And it blocked only when I tried to select the very row selected by the first transaction. I tried the following with changing ORDER BY to DESC one, it works also.

    Conclusion: MySQL blocks only the rows it actually selected when using ORDER BY and LIMIT clauses. See @Morgan answer for gap locking explanation.

    My MySQL version is 5.0.45

提交回复
热议问题