Mysql left join and sum -


i have 3 table , need sum amount separately. use fields on select or clause.

select i.*, x.* items   left join  (    select    p.item_id    ,sum(p.amount) saleamount    ,sum(if(p.type=1,pa.amount,0)) paidamount    payments p    left join payment_actions pa on pa.payment_id=p.id    group p.id ) x on x.item_id=i.id 

items table;

id   --- 1 

payments table;

id  |   item_id |   amount --------------------------- 1   |   1       |   300  

payment_actions table;

id  |   payment_id  |   amount --------------------------- 1   |   1           |   100  1   |   1           |   50 

the result should be;

saleamount  | paidamount --------------------------     300     |   150 

here easy way desired result

select   i.id,   p.amount,   pa.amount items   left join (select            id,            item_id,            sum(amount)    amount          payments          group item_id) p     on p.item_id = i.id   left join (select            payment_id,            sum(amount)    amount          payment_actions) pa     on pa.payment_id = p.id group i.id 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -