[英]Update large number of row in MySQL table
I'm using relational database(MySQL 5.7).我正在使用关系数据库(MySQL 5.7)。 On this database i have a table called customer_transaction.在这个数据库上,我有一个名为 customer_transaction 的表。 On this table i have 4 columns: id, customer_id, type, amount在这张表上,我有 4 列: id、customer_id、type、amount
|id|customer_id |type |amount|
|--|------------|---------|------|
|1 |44 |Credit |50 |
|2 |44 |Credit |20 |
|3 |44 |Debit |30 |
|4 |10 |Credit |30 |
now i am introduce a new balance column(current balance) on this table like below.现在我在这个表上引入一个新的余额列(当前余额),如下所示。
|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 |
The problem is, on the customer transaction table, their was nearly millions of row and all balance column was 0.00 .问题是,在客户交易表上,他们有近百万行,所有余额列都是0.00 。
So i want to re-sync all balance data.所以我想重新同步所有余额数据。 But i'm confused how to recalculate and update all those row.但我很困惑如何重新计算和更新所有这些行。 Can i update this by MySQL query or calculate and update from my application (Laravel-PHP).我可以通过 MySQL 查询或从我的应用程序(Laravel-PHP)计算和更新来更新它吗?
In MySQL 5.x, where window functions are not available, an option uses a correlated subquery to compute the balance:在 MySQL 5.x 中,window 函数不可用,选项使用相关子查询来计算余额:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.