【问题标题】:MySQL update with nested select使用嵌套选择更新 MySQL
【发布时间】:2017-04-26 05:58:21
【问题描述】:

我有 2 个具有以下结构的表。

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

【问题讨论】:

  • 在什么情况下它不起作用?您是否收到语法错误或未给出预期结果?
  • 不要认为你需要最后一个 WHERE 子句,因为链接已经在子选择中定义。
  • @P.Salmon,查询正常,错误为 0,但没有更新任何记录

标签: mysql


【解决方案1】:

您的查询“有效”,但如果余额以 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)

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 2011-05-16
    • 2014-05-17
    • 1970-01-01
    • 2017-11-01
    • 2019-01-06
    • 2014-07-11
    • 2020-04-26
    相关资源
    最近更新 更多