如何结合多对多加入?

时间:2013-08-17 16:52:01

标签: mysql join

表:

cust table:    
   cust_id, name, etc    

bill table:    
   bill_id, cust_id, amt, due_date, status (open/closed)

payment table:    
   payment_id, bill_id, amt etc

客户可以通过分期付款来结算单笔账单。因此,一个bill_id可能与payment_ids有关。

我无法生成此记录集:


cust_id |到期了


'due amt'是所有bill.amts的总和 - 所有payment.amts和已打开状态的总和。

比尔表

bill_id cust_id     amt     status
1       18          200     open
2       18          200     open
3       17          200     open
4       17          200     open
5       17          200     open
6       17          200     closed

付款表

payment_id  bill_id cust_id amt
1           1       18      50
2           2       18      40
3           3       17      10

预期输出

cust_id     due_amt         hint/how
17          590             (600-10) .. 600 -> because one is closed
18          310             (400-(50+40))

1 个答案:

答案 0 :(得分:2)

select c.cust_id, sum(b.amt) - sum(p.amt) as due_amt
from cust c
left join bill b on b.cust_id = c.cust_id and b.status = 'open'
left join payment p on p.bill_id = b.bill_id
group by c.cust_id

SQLFiddle demo