我有一个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 |
我的预期结果是最大qty
值50
,如
-----------------------------------------
id | qty | total_invoice_qty |
-----------------------------------------
452 | 50 | 50 |
答案 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
试试这个