具有多个连接和条件的Mysql查询

时间:2015-02-23 06:51:40

标签: mysql join

我正在尝试使用关节连接四个表,这里我使用左连接来连接表,我的条件是所有商品,项目应该相同,所有网站应该是相同的。网站有多个商品,所以我想要从每张表中获得货物总数。我的查询是

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

1 个答案:

答案 0 :(得分:0)

你能把条件放在关节的尽头吗?



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)




我没有测试过您的请求,但似乎还不错。