2017-04-21 22 views
-2

我將第一個可用行給每個用戶來作爲如何在同時連接中獲得第一個可用行?

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 

我怎樣才能確保沒有第二個用戶獲得相同的ID之前,它是UPDATE d爲多久?

注意:它與INSERT無關。桌子已經在那裏了。用戶應該採取第一個可用的行。 UPDATE只是爲了跟蹤拍攝的行。

+1

如果ID是** ** auto_incremented,是**主鍵**,你不應該去關心這個。 – Dash

+0

@Maincore,除非創建另一個用戶,在更新第一個用戶之前。 –

+0

是的。只需使用auto_increment爲你照顧這個 – Strawberry

回答

1

使用transactions

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

Transactionless版本:

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 
+0

如果'affected_rows = 0'會怎麼樣?重複一遍又一遍的過程? – Googlebot

+0

由你決定。交易失敗時你會怎麼做(指@ ivanka-todorova的答案)? –

相關問題