Search code examples
phpmysqlcoalesce

Query account running balance with php


Please assist, how to write php code for the following query:

SELECT transactions_id, trn_date, trn_dt_total, trn_ct_total, trn_description, trn_bank_reference, balance
FROM
(SELECT t.*, @n := IF(@g <> transactions_id, 0, @n) + 
COALESCE(trn_dt_total,0) - COALESCE(trn_ct_total, 0) balance, @g := 
transactions_id
FROM transactions t, (SELECT @n := 0) n, (SELECT @g := 0) g
WHERE trn_building_id = 1 and trn_unit_id = 1 and trn_tenant_id = 1
ORDER BY transactions_id, trn_date)
query

My php page query

$details = $db->query();

When running the query in MySql without the "query" line i get the error:

1248 - Every derived table must have its own alias

Solution

  • The error is self explanatory. You should name an alias for the table you created. After the subquery in the parenthesis, you should write as t_name where tname would be your table alias