【问题标题】:How to update value and then return back the updated value only if it was really updated?如何更新值,然后仅在它真正更新时才返回更新的值?
【发布时间】:2022-01-29 23:04:36
【问题描述】:

我正在尝试改进支持用户现金余额的 SaaS 的 SQL。用户下单时,应从余额中扣除订单价格。

只有当用户有足够的余额时才能进行减法。如果减法完成,则查询应返回 NEW 余额,如果余额不足,则返回 NULL。

现在我实现了这个查询:

update usr_account_balance
set balance      = @new_balance := balance - AMOUNT_TO_SUBTRACT,
    last_updated = UTC_TIMESTAMP()
where user_id = 221
  and balance >= AMOUNT_TO_SUBTRACT;
select @new_balance;

此代码的问题在于,无论是否更新,它都会返回余额。但是如果之前的查询中没有任何更新,我想返回 NULL,所以我可以警告用户他的订单无法继续,因为没有足够的可用余额。

编辑 1: SaaS 运行在 PHP、wordpress 后端。

【问题讨论】:

  • 您的 SaaS 在哪种编程语言和/或哪个框架上运行
  • 它运行在 PHP,wordpress 后端。

标签: mysql sql


【解决方案1】:

查询应该会给你想要的结果

CREATE TABLE usr_account_balance (user_id int,balance DECIMAL (10,2),last_updated timestamp )
INSERT INTO usr_account_balance VALUES(221, 8.0,now())
update usr_account_balance
set balance      = IF(balance >= 10,@new_balance := balance - 10, @new_balance := balance),
    last_updated = UTC_TIMESTAMP()
where user_id = 221
  and balance >= 10;
select @new_balance;
| @new_balance | | :----------- | | |
update usr_account_balance
set balance      = IF(balance >= 7,@new_balance := balance - 7, @new_balance := balance),
    last_updated = UTC_TIMESTAMP()
where user_id = 221
  and balance >= 7;
select @new_balance;
| @new_balance | | ------------: | | 1.00 |

db小提琴here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多