[英]Unable to update values from one table to another table in mysql
ledger_id ledger_name dep_id dr_bal cr_bal
1 Purchase 2 NUll NUll
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
. 这些是我的表格,
Ledgers
和Transactions
。 I want to update ledgers.dr_bal
from transactions.amount
, based on ledger_id
which is the primary key
in ledgers
table. 我想更新
ledgers.dr_bal
从transactions.amount
基础上, ledger_id
这是primary key
的ledgers
表。
Want to copy the values from transactions.amount
to dr_bal
based on trans_type ='dr'
dr_bal
基于trans_type ='dr'
的值从transactions.amount
复制到dr_bal
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. 但是无法运行上述查询,因为它会在结尾的
Where
子句中引发错误。
Have tried looking into various questions related to updating tables here. 尝试在这里调查与更新表有关的各种问题。 But am really stuck.
但是我真的被困住了。
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. 如果要使用交易金额更新所有分类帐,请删除
tbl_transactions.ledger_id = 1
的条件,并在子查询中引入GROUP BY tbl_transactions.ledger_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.