In pratica stai calcolando il prodotto incrociato tra un tdebits e tcredits , ovvero per ogni riga in tdebits stai iterando su tutte le righe in tcredits . Inoltre, non c'è motivo per entrare in accounts (a meno che to_account_id e from_account_id non sono chiavi esterne).
Devi solo fare un passaggio sulle transazioni e devi solo sapere se l'importo è un credito o un debito.
SELECT SUM(CASE WHEN t.to_account_id = $1 THEN t.amount ELSE -t.amount END) AS amount
FROM transactions AS t
WHERE (t.to_account_id = $1 OR t.from_account_id = $1)
AND t.succeed = true
Se un account può essere trasferito su se stesso, aggiungi un t.to_account_id <> t.from_account_id .