2017-06-29 175 views
0

我想結合兩個查詢在一起,並不確定的方法。我對加入以及如何工作知之甚少。MySQL SUM減SUM和加入

我有兩個表。

用戶:

id, 
email, 
userNumber 

餘額:

id, 
userNumber, 
credit, 
debit (multiple entries in which I use SUM - SUM group by userNumber) 

我這工作得很好單獨的查詢均低於但我需要將它們結合在一起莫名其妙:

SELECT SUM(credit) - SUM(debit) as 'balance' FROM balances GROUP BY userNumber 

SELECT u.id, u.email, u.userNumber, 
g.userNumber AS groupID, 
g.debit AS debit, 
g.credit AS credit 
FROM user AS u 
LEFT JOIN balances AS g ON u.userNumber = g.userNumber 

我基本上ne編輯轉換第一個表有userNumber和平衡,然後用它來加入另一個表。第二張表不需要借方或貸方,可以用餘額代替。

回答

1

您可以使用此

SELECT u.id, u.email, u.userNumber, 
g.userNumber AS groupID, 
g.debit AS debit, 
g.credit AS credit, 
g.balance AS balance 
FROM user AS u 
LEFT JOIN (SELECT userNumber, SUM(credit) - SUM(debit) as 'balance' FROM balances GROUP BY userNumber) AS g ON u.userNumber = g.userNumber 
+0

大簡單,並集成了什麼我已經有了。不得不調整它只是一點點工作,必須刪除g.debt AS債務和g.credit作爲信貸,因爲那些沒有在第二選擇被稱爲。 – webbernaut

0

不知道你想要什麼確切的格式,我可以建議你只是LEFT JOIN你的第一個聚合子查詢到第二個。

SELECT 
    u.id, 
    u.email, 
    u.userNumber, 
    g.userNumber AS groupID, 
    COALESCE(g.debit, 0) AS debit, 
    COALESCE(g.credit, 0) AS credit, 
    COALESCE(t.balance, 0) AS balance 
FROM user AS u 
LEFT JOIN balances AS g 
    ON u.userNumber = g.userNumber 
LEFT JOIN 
(
    SELECT userNumber, SUM(credit) - SUM(debit) AS balance 
    FROM balances 
    GROUP BY userNumber 
) t 
    ON u.userNumber = t.userNumber