2014-02-25 59 views
1

總和,如果有2個表:MySQL的計算從2頁不同的表

TABLE "deposit" 
card | amount 
------------ 
2 | 123.43 
2 | 56.45 
3 | 21.19 

+

TABLE "payment" 
card | price | status 
----------- 
2 | 10.59 | finish 
2 | 10.59 | pending 
10 | 12.40 | finish 
2 | 10.59 | finish 

我尋找的是一個卡ID餘款。

爲卡2實施例:123.43 + 56.45 - 10.59 - 10.59(僅狀態=光潔度)

或:SUM(存款對於卡ID = 2) - SUM(支付卡ID = 2和狀態=完成)

我嘗試以下的mysql-選擇:

SELECT(
     IFNULL(SUM(deposit.amount),0) - IFNULL(SUM(payment.price),0) 
     ) AS remaing_deposit 
     FROM deposit, payment 
     WHERE deposit.card = '2' 
     OR (
      payment.card = '2' AND payment.status = 'finish' 
     ) 

,但我得到完全錯誤的號碼。

任何人都可以幫助我嗎?

+0

你似乎缺少一些主鍵! – Strawberry

回答

2

這裏的一個挑戰是兩張桌子有不同的卡片。 MySQL不支持full outer join。你可以得到一張union的卡片清單。

查詢的其餘部分通過allcards使用left outer join聚合兩個表from子句中的d解決:

select allcards.card, coalesce(d.deposit, 0) - coalesce(p.price, 0) as RemainingDeposit 
from (select card from deposit union 
     select card from payment 
    ) allcards left outer join 
    (select card, sum(amount) as deposit 
     from deposit 
     group by card 
    ) d 
    on d.card = allcards.card left outer join 
    (select card, sum(price) as price 
     from payment 
     where status = 'finish' 
     group by card 
    ) p 
    on p.card = allcards.card; 
+0

謝謝你的快速幫助!它工作完美! **我添加「WHERE card = 2」來獲取一張卡的剩餘存款。** – mdunisch