如何在同时连接中获取第一个可用行?

时间:2017-04-21 13:09:50

标签: php mysql

我将第一个可用行分配给每个即将到来的用户

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

如何确保第二个用户在UPDATE d之前没有检索到相同的ID?

注意:它与INSERT无关。桌子已经存在了。用户应该使用第一行。 UPDATE只是为了跟踪拍摄的行。

2 个答案:

答案 0 :(得分:1)

使用transactions

start transaction;
SELECT @A:=id FROM table1 ORDER BY id LIMIT 1
UPDATE table1 SET status='taken' WHERE id=@A
commit;

答案 1 :(得分:0)

无交易版:

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