-2

I assign the first available row to each coming user as

SELECT id FROM table1 WHERE status IS NULL ORDER BY id LIMIT 1
fetched id is xxx
UPDATE table1 SET status='taken' WHERE id=xxx

How can I make sure that not a second user retrieve the same id before it is UPDATEd as taken?

NOTE: It has nothing to do with INSERT. The table is already there. Users should take the first available row. UPDATE is just to keep track of taken rows.

Googlebot
  • 14,156
  • 43
  • 126
  • 219

2 Answers2

1

Use transactions:

start transaction;
SELECT @A:=id FROM table1 ORDER BY id LIMIT 1
UPDATE table1 SET status='taken' WHERE id=@A
commit;
Ivanka Todorova
  • 9,533
  • 15
  • 56
  • 97
0

Transactionless version:

SELECT id FROM table1 WHERE status != 'taken' ORDER BY id LIMIT 1
fetched id is xxx
UPDATE table1 SET status='taken' WHERE id=xxx AND status != 'taken'
check number of affected rows
Alex Blex
  • 29,922
  • 5
  • 40
  • 70