How to properly avoid Mysql Race Conditions

前端 未结 3 650
既然无缘
既然无缘 2021-01-06 02:53

I know this has been asked before, but I\'m still confused and would like to avoid any problems before I go into programming if possible.

I plan on having an interna

3条回答
  •  孤独总比滥情好
    2021-01-06 03:39

    When you post a row, set the column to NULL, not 0.

    Then when a user updates the row to make it their own, update it as follows:

    UPDATE MyTable SET ownership = COALESCE(ownership, $my_user_id) WHERE id = ...
    

    COALESCE() returns its first non-null argument. So even if you and I are updating concurrently, the first one to commit gets to set the value. The second one will not override that value.

提交回复
热议问题