使用嵌套选择进行MySQL更新

时间:2017-04-26 05:58:21

标签: mysql

我有两张表,结构如下。

Accounts (acc_id, name, balance)
GeneralLedger GL (account_id, voucher_id, debit,credit)

我想通过计算总帐表中的总借记和总贷记来更新帐户表中的帐户余额。

我尝试了下面的查询,但它没有工作,没有错误,但没有更新任何记录

UPDATE accounts a
INNER JOIN
(
  SELECT gl.account_id, SUM(gl.debit) total_debit, SUM(gl.credit) total_credit
  FROM general_ledger gl
  WHERE gl.voucher_id=1
  GROUP BY  gl.account_id
) gl ON gl.account_id=a.account_id

SET a.balance = a.balance + (total_credit-total_debit)
WHERE a.acc_id=gl.account_id

1 个答案:

答案 0 :(得分:0)

您的查询“有效”,但如果余额以null开头,则添加到null会导致null,您可以通过在set语句中使用coalesce或在表定义中将其默认为0来捕获它。此外,没有a.account_id这样的字段,因此您应该将其更改为a.acc_id。

DROP TABLE IF EXISTS Accounts, generalledger ;

create table accounts(acc_id int, name varchar(3), balance int);
create table generalledger(account_id int, voucher_id int, debit int,credit int);

insert into accounts values (1,'aaa',null),(2,'bbb',100);

insert into generalledger values
(1,1,10,null),(1,1,null,20),
(2,1,10,null),(2,1,null,10);

UPDATE accounts a
INNER JOIN
(
  SELECT gl.account_id, SUM(gl.debit) total_debit, SUM(gl.credit) total_credit
  FROM generalledger gl
  WHERE gl.voucher_id=1
  GROUP BY  gl.account_id
) gl ON gl.account_id=a.acc_id

SET a.balance = coalesce(a.balance,0) + (total_credit-total_debit)
;
select * from accounts; 

MariaDB [sandbox]> select * from accounts;
+--------+------+---------+
| acc_id | name | balance |
+--------+------+---------+
|      1 | aaa  |      10 |
|      2 | bbb  |     100 |
+--------+------+---------+
2 rows in set (0.00 sec)