How to deal with concurrent updates in databases?

后端 未结 9 1753
名媛妹妹
名媛妹妹 2020-11-27 12:24

What\'s the common way to deal with concurrent updates in an SQL database ?

Consider a simple SQL schema(constraints and defaults not shown..) like

c         


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 13:02

    For MySQL InnoDB tables, this really depends on the isolation level you set.

    If you are using the default level 3 (REPEATABLE READ), then you would need to lock any row that affects subsequent writes, even if you are in a transaction. In your example you will need to :

    SELECT FOR UPDATE creds FROM credits WHERE userid = 1;
    -- calculate --
    UPDATE credits SET creds = 150 WHERE userid = 1;
    

    If you are using level 4 (SERIALIZABLE), then a simple SELECT followed by update is sufficient. Level 4 in InnoDB is implemented by read-locking every row that you read.

    SELECT creds FROM credits WHERE userid = 1;
    -- calculate --
    UPDATE credits SET creds = 150 WHERE userid = 1;
    

    However in this specific example, since the computation (adding credits) is simple enough to be done in SQL, a simple:

    UPDATE credits set creds = creds - 150 where userid=1;
    

    will be equivalent to a SELECT FOR UPDATE followed by UPDATE.

提交回复
热议问题