增加数量但不多于主数量字段

时间:2016-11-18 06:22:40

标签: mysql sql

我有一个mysql表proforma_invoice_items

-----------------------------------------
    id  |   qty |   total_invoice_qty   |
-----------------------------------------
    452 |   50  |   45                  |

现在,我想用total_invoice_qty增加10值,但不是qty值增加50

我试过下面的查询:

update proforma_invoice_items a set a.total_invoice_qty = a.total_invoice_qty+10 where a.id = 452 and a.total_invoice_qty < a.qty

结果是:

-----------------------------------------
    id  |   qty |   total_invoice_qty   |
-----------------------------------------
    452 |   50  |   55                  |

我的预期结果是最大qty50,如

-----------------------------------------
    id  |   qty |   total_invoice_qty   |
-----------------------------------------
    452 |   50  |   50                  |

5 个答案:

答案 0 :(得分:1)

您可以使用LEAST()

  

使用两个或多个参数,返回最小值(最小值)   参数。

UPDATE proforma_invoice_items a
SET a.total_invoice_qty = LEAST(a.total_invoice_qty + 10, a.qty)
WHERE a.id = 452

答案 1 :(得分:1)

UPDATE proforma_invoice_items 
SET total_invoice_qty  =  CASE WHEN total_invoice_qty  + 10 > qty THEN qty
                               ELSE  total_invoice_qty  + 10 END
WHERE id = 452

答案 2 :(得分:0)

希望以下查询可以帮助您

update proforma_invoice_items a 
set a.total_invoice_qty = 
            a.total_invoice_qty + (Case WHEN a.qty - a.total_invoice_qty >= 0 THEN 10 ELSE a.qty - a.total_invoice_qty END)  where a.id = 452 and a.total_invoice_qty < a.qty

答案 3 :(得分:0)

通用查询不能像WHERE id = 452那样进行硬编码,请尝试使用

UPDATE proforma_invoice_items  
SET total_invoice_qty  = CASE
   WHEN  (total_invoice_qty+10) < 50 THEN total_invoice_qty+10
   ELSE 50
END

答案 4 :(得分:-1)

update proforma_invoice_items a set a.total_invoice_qty = case when a.total_invoice_qty+10 < a.total_invoice_qty then a.total_invoice_qty+10 else a.total_invoice_qty end  where a.id = 452 and a.total_invoice_qty < a.qty

试试这个