Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
更新MySQL表中的大量行_Mysql_Sql_Sql Update_Large Data - Fatal编程技术网

更新MySQL表中的大量行

更新MySQL表中的大量行,mysql,sql,sql-update,large-data,Mysql,Sql,Sql Update,Large Data,我使用的是关系数据库MySQL 5.7。在这个数据库中,我有一个名为customer\u transaction的表。在这个表中,我有4列:id、customer\u id、type、amount 现在,我将在下表中介绍一个新的余额栏Current balance(当前余额) |id|customer_id |type |amount|balance| |--|------------|---------|------|-------| |1 |44 |Credit

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

现在,我将在下表中介绍一个新的余额栏Current balance(当前余额)

|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 transaction表上,它们的行数接近数百万行,而所有余额列都是0.00


所以我想重新同步所有余额数据。但我不知道如何重新计算和更新所有这些行。我可以通过MySQL查询或通过我的应用程序Laravel PHP进行计算和更新

在MySQL 5.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

是的,你能做到。使用会话变量保存前一行的运行余额,并根据类型是贷方还是借方进行添加或减去。当customer_id`更改时,您会将变量设置回0。但这是一个问题。我们在实时服务器上执行这些过程,需要一些时间才能执行。我认为,在执行期间,我的事务表保持锁定状态。它们是否有任何防止锁定的方法。
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