mysql insert race condition

后端 未结 8 1431
暗喜
暗喜 2020-12-09 06:19

How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:

  1. select a row from table
  2. if it doesn\'t exist, insert it
8条回答
  •  温柔的废话
    2020-12-09 06:40

    In case insert ignore doesnt fit for you as suggested in the accepted answer , so according to the requirements in your question :

    1] select a row from table
    2] if it doesn't exist, insert it

    Another possible approach is to add a condition to the insert sql statement, e.g :

    INSERT INTO table_listnames (name, address, tele)
    SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
    WHERE NOT EXISTS (
        SELECT name FROM table_listnames WHERE name = 'Rupert'
    ) LIMIT 1;
    

    Reference: https://stackoverflow.com/a/3164741/179744

提交回复
热议问题