更新mysql表中的大量行

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

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

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

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

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

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

ikfrs5lh

ikfrs5lh1#

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

  1. update customer_transaction ct
  2. inner join (
  3. select
  4. id,
  5. (
  6. select sum(case type when 'Credit' then amount when 'Debit' then -amount end)
  7. from customer_transaction ct2
  8. where ct2.customer_id = ct1.customer_id and ct2.id <= ct1.id
  9. ) balance
  10. from customer_transaction ct1
  11. ) ctx on ctx.id = ct.id
  12. set ct.balance = ctx.balance

相关问题