今天研究一個主題,扣庫存,看到一個關鍵詞組
“select for update mysql”
看了幾個人的寫法
整合起來就是這樣
table : tb1
欄位
id
stock
扣庫存
BEGIN;
select stock from tb1 where id=1 for update;
update tb1 set stock = stock -2 where id =1 and stock >=2;
commit;
故意用2…為了是顯示要扣庫存的條件,這裡的條件是扣兩件所以where stock>=2才能跑stock -2
使用transation時 測試的結果
開兩個視窗
conn a
conn b
conn a執行
BEGIN;
select stock from tb1 where id=1 for update;
update tb1 set stock = stock -1 where id =1 and stock >=1;
再來
conn b執行
update tb1 set stock = stock -1 where id =1 and stock >=1;
這時候conn b會等到conn a comit之後才會扣庫存
conn a 執行commit;
transcation結束
換執行 conn b
如果庫存被扣完 那就會更新失敗傳回0
現在的問題是
扣庫存要用哪一種語法呢?
stock = stock -1
還是
sotck = $a
前者看起來比較沒有庫存錯誤的問題,但必須配合transaction使用
至於$a的值也是從select來的,可能會有時間差的問題
mysql 官網在介紹for update這件事情的時候,是用stock = stock -1當範例的,終究這是最後的值,沒有經過select的時間差
最後這只有innodb才做的了….