从MySQL数据库中减去数量而不会变为负数

时间:2015-10-17 01:12:47

标签: c# mysql

我正在编写一个C#应用程序,每次发布本书时,它会将数据库中特定书籍的数量减少1。数量不断减去,直到最终以负值作为账面数量。

我想知道如何在不达到负值的情况下减去图书数量。

以下是代码:

R[0,0]

2 个答案:

答案 0 :(得分:0)

只需使用casegreatest()

即可
update tblbooks
    set quantity = greatest(quantity - 1, 0)
    where book_id = @book_id;

或者,更好的是,使用where中的条件:

update tblbooks
    set quantity = quantity - 1
    where book_id = @book_id and quantity >= 1;

答案 1 :(得分:0)

在class中使用以确保仅更新具有quantity > 0

的记录
update tblbooks 
set quantity=quantity - 1 
where quantity>0 and book_id=@book_id