简体   繁体   中英

Mysql query with multiple joins and conditions

I am trying to connect four tables using joints,here i used left join to connect tables and my condition is all the goods,item should be same and all the site should be same.same site have multiple goods, so i want to get the sum number of goods from each table. my query is given

select 
    a.goods
    ,sum(a.no_of_units) as totala
    , a.site
    ,b.item
    ,sum(b.quantity) as totalb
    ,b.site
    ,c.goods
    ,c.site
    ,sum(c.no_of_units) as totalc
    ,d.site
    ,d.goods
    ,sum(d.quantity)b as totald 
from 
    inward_stock a 
left join 
    opening_balance b 
on 
    a.site=b.site 
and 
    a.goods=b.item 
left join 
    return_stock c 
on 
    b.site=c.site 
and 
    b.item=c.goods 
left join 
    stock_consumed d 
on 
    d.site=c.site
and 
    d.goods=c.goods

Can you put your conditions at the end of the joints like this:

 select a.goods,sum(a.no_of_units) as totala, a.site,b.item,sum(b.quantity) as totalb,b.site,c.goods,c.site,sum(c.no_of_units) as totalc,d.site,d.goods,sum(d.quantity) as totald from inward_stock a left join opening_balance b on (a.site=b.site) left join return_stock c on (b.site=c.site) left join stock_consumed d on (d.site=c.site) where (a.goods=b.item) and (b.item=c.goods) and (d.goods=c.goods) 

I have not tested your request but it seems that it's not bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM