Mysql
 sql >> Datenbank >  >> RDS >> Mysql

SQL-Abfrage zur Berechnung des Kontostands

Sie berechnen im Grunde das Kreuzprodukt zwischen tdebits und tcredits , also für jede Zeile in tdebits Sie iterieren über alle Zeilen in tcredits . Es gibt auch keinen Grund, accounts beizutreten (es sei denn, to_account_id und from_account_id sind keine Fremdschlüssel).

Sie müssen nur eine Transaktion durchlaufen und wissen, ob es sich bei dem Betrag um eine Gutschrift oder eine Belastung handelt.

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

Wenn ein Konto auf sich selbst übertragen werden kann, fügen Sie eine t.to_account_id <> t.from_account_id hinzu .