Search code examples
mysqlaccounting

mysql: running an insert based two other row's value


I have a table with columns: debit, credit, debit_balance, credit_balance, and amount. Debit and credit each pertain to specific accounts.

Each time I add a new row, I want the debit_balance and credit_balance to be assigned based on the account's previous balance.

INSERT INTO `ledger` (`debit`, `credit`, `debit_balance`, `credit_balance`, `amount`) 
VALUES ('1', '3', 
(SELECT debit_balance FROM `ledger` WHERE `debit` = '1' ORDER BY `id` DESC LIMIT 0,1) + 5, 
(SELECT credit_balance FROM `ledger` WHERE `credit` = '3' ORDER BY `id` DESC LIMIT 0,1) + 5,
'5')

Where debit's account is 1, credit's account is 3, and the amount I want to change is 5.

When I run the query, mysql gives me a Every derived table must have its own alias error.


Solution

  • You can use a single SELECT query to provide the values to be inserted.

    INSERT INTO ledger (debit, credit, debit_balance, credit_balance, amount)
    SELECT 1, 3, l1.debit_balance + 5, l2.credit_balance + 5, 5
    FROM (SELECT MAX(id) AS debit_id FROM ledger WHERE debit = 1) AS maxd
    JOIN ledger AS l1 ON l1.id = maxd.debit_id
    CROSS JOIN (SELECT MAX(id) AS credit_id FROM ledger WHERE credit = 3) AS maxc
    JOIN ledger AS l2 ON l2.id = maxc.credit_id