具有聚合函数的多个mysql JOIN

时间:2012-07-05 02:57:29

标签: sql

我试图加入3个表

文章,股票和已售表 enter image description here

我想为每篇文章选择表格中的QteEntree和它的总和 来自桌子的Qte已售出 这是我的代码

Select  Article.IdArt,
        Sum(sold.Qte),
        Sum(Stock.QteEntree)
from (((Article) 
        Left Join Sold on Sold.IdArt = Article.IdArt)
        Left Join Stock on Stock.IdArt = Article.IdArt)
Group by Article.IdArt

但我总是得到(例如)QteEntree的IdArt乘法结果为2 为Qte乘以3的结果 我猜是因为我在Sold表中有2条记录,在Stock表中有3条记录

我该如何解决这个问题?

thx

1 个答案:

答案 0 :(得分:5)

使用子查询进行拍摄:

select a.IdArt,
       (select sum(Qte) from Sold where IdArt = a.IdArt group by IdArt) as QteSum,
       (select sum(QteEntree) from Stock where IdArt = a.IdArt group by IdArt) as QteEntreeSum
from Article a