I created a stored-procedure that updates the balances of the Handle table. At first I tried to use From Movimentacao
within the update
of the move, only that returned error. I fixed this problem by doing FROM (SELECT * FROM Movimentacao) as L2
. But this caused another problem: slowness if the table is too large, because it gets SELECT * FROM Movimentacao
all the time. I tested with 10000 records and got very slow. I was breaking my head to build a query that was quick in the update with select , but it's a bit difficult.
Follow the stored-procedure code in MySql:
BEGIN
set @a:=0;
update Movimentacao d set d.ordem = (select @a:=@a+1) where id_conta = wconta
order by data;
UPDATE Movimentacao set saldo= (SELECT SUM(IF(operacao = 'Entrada', valor, -valor))
FROM (SELECT * FROM Movimentacao) as L2
WHERE L2.ordem <= Movimentacao.ordem and id_conta = wconta order by data,ordem)
WHERE id_conta = wconta
ORDER BY data,ordem;
END