2017-04-26 164 views
0

我有兩個表,其結構如下。帶有嵌套選擇的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 
+0

它以什麼方式不起作用?你會得到一個語法錯誤還是不會給出預期的結果? –

+0

不要以爲你需要最後一個WHERE子句,因爲鏈接已經在子選擇中定義。 –

+0

@P.Salmon,查詢與0錯誤正常,但它不更新任何記錄 – user3554045

回答

0

您所查詢的「作品」,但如果天平開始爲空,則加劇了空空的結果,你可以通過在您的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) 
+0

非常感謝你 – user3554045