Para versões de MySQL >= 8.0, WITH RECURSIVE Q (rowid, data, fornecedor, credito, debito, saldo) AS ( SELECT C.id, C.data, C.fornecedor, HCRED.valor_pago as credito, HDEB.valor_pago as debito, COALESCE(HDEB.valor_pago, 0) + COALESCE(HCRED.valor_pago, 0) as saldo FROM tb_compras C LEFT JOIN tb_compras_historico_pagamento HCRED ON C.id = HCRED.id_compra AND HCRED.valor_pago > 0 LEFT JOIN tb_compras_historico_pagamento HDEB ON C.id = HDEB.id_compra AND HDEB.valor_pago < 0 UNION SELECT C.data, C.fornecedor, HCRED.valor_pago, HDEB.valor_pago, COALESCE(HCRED.valor_pago, 0) + COALESCE(HDEB.valor_pago, 0) + Q.saldo FROM tb_compras C JOIN Q ON C.id = Q.rowid + 1 LEFT JOIN tb_compras_historico_pagamento HCRED ON C.id = HCRED.id_compra AND HCRED.valor_pago > 0 LEFT JOIN tb_compras_historico_pagamento HDEB ON C.id = HDEB.id_compra AND HDEB.valor_pago < 0 ) SELECT * FROM Q ORDER BY 2, 3;