MySQL Update query - Will the 'where' condition respected on race condition and row locking? (php, PDO, MySQL, InnoDB)

前端 未结 3 2010
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-09 03:59

I am trying to build a first-come first-get model sale page. We have n number of items of the same type. We want to assign these n items to the first n users who made the reques

3条回答
  •  梦谈多话
    2021-02-09 04:19

    The answer is: it will validate the WHERE condition before updating the data.


    Well, I have to say that this is a very interesting question. I've never thought about such a question before, and it enforces me to have a better understanding of how it works inside MySQL. Thank you!

    How I get the answer:

    I did my test for this situation at first. I know it should work like this even before I did my test, but I just didn't understand why.

    Why:

    Finally, I found something useful in the Index Condition Pushdown section.

    This is how it works inside MySQL:

    MySQL Server
       ↑  ↑
       ↓  ↓
    Storage Engine(InnoDB here)
    
    1. MySQL Server parses SQL statements coming from external applications.
    2. MySQL Server tells InnoDB to retrieve rows for it.
    3. InnoDB locates rows(Index, Locking), then return them to MySQL Server.
    4. MySQL Server evaluates WHERE conditions for rows.
    5. Some other things ...

    As you can see, locking occurs inside InnoDB, and MySQL Server evaluates the WHERE condition after obtaining the rows. For your situation, the row(id = 5) is locked by the first UPDATE, and the second UPDATE gets stuck when fetching the same row. And the evaluation for the second UPDATE's WHERE condition occurs after obtaining the lock for the row.

    What's more, if you have created an index on id, Index Condition Pushdown will take place in your query.

提交回复
热议问题