Reputation: 2823
hey guys I have got a MySQL query that reduces stock every button click,
Query
UPDATE Animals
SET Stock = Stock - 1
WHERE Specie ='{1}' and Country ='{0}'
problem is I wish for it to stop at 0 and not go into negative is there a way to do this?
Upvotes: 1
Views: 806
Reputation: 2541
In cases where you want to decrement the inventory by more than one -
'{2}'
here, refers to the quantity to be decremented.
UPDATE Animals
SET Stock = Stock - '{2}'
WHERE
Specie ='{1}' and Country ='{0}'
AND Stock - '{2}' >= 0
Upvotes: 0
Reputation: 53840
To prevent over-ordering, you might want to check to see if there's actually stock, hold it in reserve, then make your decision, by using a transaction:
START TRANSACTION;
SELECT Stock
FROM Animals
WHERE Specie ='{1}' and Country ='{0}' AND Stock > 0
FOR UPDATE;
If you didn't get a record, the stock is <= 0. If you get a record, you've got the remaining stock count.
Now update it:
UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}';
COMMIT;
Otherwise,
ROLLBACK;
You'll want to do this over the same session (connection).
Upvotes: 1
Reputation: 4221
This should work:
"UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}' and Stock >0"
Upvotes: 3
Reputation: 254926
UPDATE Animals
SET Stock = Stock - 1
WHERE Specie ='{1}' and Country ='{0}' AND Stock > 0
So restrict the row to have Stock > 0
explicitly
Upvotes: 6