MySQL INSERT IF (custom if statements)

前端 未结 5 1454
后悔当初
后悔当初 2020-11-27 04:37

First, here\'s the concise summary of the question:

Is it possible to run an INSERT statement conditionally? Something akin to this:

IF(         


        
5条回答
  •  旧巷少年郎
    2020-11-27 05:05

    Not sure about concurrency, you'll need to read up on locking in mysql, but this will let you be sure that you only take 20 items if 20 items are available:

    update products 
    set qty_on_hand = qty_on_hand - 20 
    where qty_on_hand >= 20
    and id=2
    

    You can then check how many rows were affected. If none were affected, you did not have enough stock. If 1 row was affected, you have effectively consumed the stock.

提交回复
热议问题