Locking a row in a MYSQL table during a transaction

后端 未结 1 1822
故里飘歌
故里飘歌 2021-01-15 11:44

I have a batch of queries like this:

START TRANSACTION
SELECT amount FROM piggybank WHERE id = 2
UPDATE piggybank SET amount = amount + 5 WHERE id = 1
COMMIT         


        
相关标签:
1条回答
  • 2021-01-15 11:49

    using a select ... for update query inside the transaction should give you the semantics you want - other updates will be locked, and other sessions attempting to take this same lock will block until you commit:

    START TRANSACTION
    SELECT * FROM piggybank WHERE id IN (1, 2) FOR UPDATE;
    SELECT amount FROM piggybank WHERE id = 2;
    UPDATE piggybank SET amount = amount + 5 WHERE id = 1;
    COMMIT
    
    0 讨论(0)
提交回复
热议问题