在MySQL中减少停止在0

时间:2013-11-26 21:18:33

标签: mysql decrement

嘿伙计们,我有一个MySQL查询,可以减少每次点击按钮的库存,

查询

UPDATE Animals 
   SET Stock = Stock - 1 
 WHERE Specie ='{1}' and Country ='{0}'          

问题是我希望它停在0并且没有进入否定是否有办法做到这一点?

5 个答案:

答案 0 :(得分:5)

UPDATE Animals
   SET Stock = Stock - 1
 WHERE Specie ='{1}' and Country ='{0}' AND Stock > 0

因此,要明确限制行Stock > 0

答案 1 :(得分:2)

这应该有效:

 
 "UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}' and Stock >0"
 

答案 2 :(得分:1)

为了防止过度订购,您可能需要检查是否存在实际库存,保留它,然后通过使用交易做出决定:

START TRANSACTION;
SELECT Stock
  FROM Animals
  WHERE Specie ='{1}' and Country ='{0}' AND Stock > 0
  FOR UPDATE;

如果您没有获得记录,则该股票<= 0.如果您获得了记录,您将获得剩余的库存数量。

现在更新它:

 UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}';
 COMMIT;

否则,

 ROLLBACK;

您希望在同一会话(连接)上执行此操作。

答案 3 :(得分:0)

... SET Stock = IF(Stock < 1, Stock, Stock -1)...

答案 4 :(得分:0)

如果您要减少库存量不止一个-

'{2}'是指要减少的数量。

UPDATE Animals
  SET Stock = Stock - '{2}'
  WHERE 
     Specie ='{1}' and Country ='{0}' 
     AND Stock - '{2}' >= 0