更新mysql表中的大量行

qnzebej0  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(243)

我正在使用关系数据库(mysql 5.7)。在这个数据库中,我有一个名为customer\u transaction的表。在这个表中我有4列:id,customer,type,amount

|id|customer_id |type     |amount|
|--|------------|---------|------|
|1 |44          |Credit   |50    |
|2 |44          |Credit   |20    |
|3 |44          |Debit    |30    |
|4 |10          |Credit   |30    |

现在我将在下表中引入一个新的余额列(当前余额)。

|id|customer_id |type     |amount|balance|
|--|------------|---------|------|-------|
|1 |44          |Credit   |50    |50     |
|2 |44          |Credit   |20    |70     |
|3 |44          |Debit    |30    |40     |
|4 |10          |Debit    |30    |-30    |

问题是,在customer事务表上,它们的行数接近数百万,而所有余额列都是0.00。
所以我想重新同步所有余额数据。但我不知道如何重新计算和更新所有这些行。我可以通过mysql查询更新这个,或者从我的应用程序(laravelphp)计算并更新。

ikfrs5lh

ikfrs5lh1#

在MySQL5.x中,窗口函数不可用,选项使用相关子查询来计算余额:

update customer_transaction ct
inner join (
    select 
        id, 
        (
            select sum(case type when 'Credit' then amount when 'Debit' then -amount end)
            from customer_transaction ct2
            where ct2.customer_id = ct1.customer_id and ct2.id <= ct1.id
        ) balance
    from customer_transaction ct1
) ctx on ctx.id = ct.id
set ct.balance = ctx.balance

相关问题