添加一个JOIN语句会更改先前总和的值

时间:2013-12-18 19:33:56

标签: mysql

我在sqlfiddle中有这个查询,它提供了正确的值

但是当我添加一个左连接表时,结果会发生变化(我尝试使用右边和内部连接相同的结果)并且它在sqlfiddle

添加stockdata时,我在此查询中错过了哪些内容?

有3张表defmatiere,成分和stockdata

当我使用此查询时:

SELECT dm.nom,SUM(IF(dm.id=ig.matid AND ig.matcuisine= 3,ig.qty,0)) AS bisused
FROM ingredient AS ig
LEFT JOIN DefMatiere AS dm ON ig.matid=dm.id AND ig.matcuisine=3 
WHERE dm.id=ig.matid AND dm.type=1 GROUP BY dm.nom

我得到了更正总和

但是当我使用这个查询时

SELECT dm.nom,SUM(IF(dm.id=ig.matid AND ig.matcuisine= 3,ig.qty,0)) AS bisused,
SUM(DISTINCT IF(dm.id=sd.matid, sd.quantite,0)) AS bisbought
FROM ingredient AS ig 
LEFT JOIN DefMatiere AS dm ON ig.matid=dm.id AND ig.matcuisine=3 
LEFT JOIN StockData AS sd ON sd.matid=dm.id
WHERE dm.id=ig.matid AND dm.type=1 GROUP BY dm.nom

bisused的总和加倍,其余的是正确的

0 个答案:

没有答案