Search code examples
mysqlaccounts

Unable to update values from one table to another table in mysql


Ledgers Table

ledger_id   ledger_name dep_id  dr_bal   cr_bal
   1          Purchase     2     NUll     NUll

Transaction Table

trans_id    trans_date  ledger_id   ledger_name    amount   trans_type
1            3/2/2004      1        Purchase A/C    84500   dr
2            3/12/2004     6         Cash A/C       20000   cr 

These are my tables, Ledgers and Transactions. I want to update ledgers.dr_bal from transactions.amount, based on ledger_id which is the primary key in ledgers table.

Want to copy the values from transactions.amount to dr_bal based on trans_type ='dr'

So far I have tried doing ,

UPDATE ledgers
SET dr_bal =(select sum(If(tbl_transactions.trans_type = 'dr' AND transactions.ledger_id = 1), amount,0) FROM transactions)
where ledgers.ledger_id =1;

But am unable to run the above query, as it throws an error at the Where clause at the end.

Have tried looking into various questions related to updating tables here. But am really stuck.


Solution

  • Try this query!

    UPDATE ledgers
            LEFT JOIN
        (SELECT 
            SUM(amount) soa, ledger_id
        FROM
            tbl_transactions
        WHERE
            tbl_transactions.trans_type = 'dr'
                AND tbl_transactions.ledger_id = 1) t ON (ledgers.ledger_id = t.ledger_id) 
    SET 
        ledgers.dr_bal = coalesce(t.soa, 0);
    

    If you would like to update all ledgers with the transactions amount, remove the condition of tbl_transactions.ledger_id = 1 and introduce GROUP BY tbl_transactions.ledger_id in the sub-query.