2013-08-01 111 views
0

我有这样的查询,并成功获取了totstock从其他两个表中选择SUM

SELECT p.pid,p.product_name,SUM(s.qty) as totstock 
FROM tblproducts p 
LEFT JOIN tblstocks s ON s.pid=p.pid 
GROUP BY p.pid 

但是当我试图加入我的第二个表它得到错误的总totstocktotsales 我有这个疑问,但我认为它是错误的

SELECT p.pid,p.product_name,SUM(s.qty) as totstock,SUM(sl.qty) as totsale 
FROM tblproducts p 
LEFT JOIN tblstocks s ON s.pid=p.pid 
LEFT JOIN tbls sl ON sl.pid=p.pid 
GROUP BY p.pid 

产品 - tblproducts

pid | product_name 
1 | pencil 
2 | paper 

股票 - tblstocks

pid | qty 
1 | 1 
1 | 3 
1 | 5 

销售 - tbls

pid | qty 
    1 | 2 
    1 | 1 

我要的结果是

pid | name | totstock | totsales 
1 | pencil | 9  | 3 
2 | paper | NULL | NULL 
+0

'totstock'和'totsales'不仅仅是我想要的结果。我想一倍或三倍 – kashimu

回答

3
SELECT p.pid,p.product_name,totstock, totsale 
FROM tblproducts p 
LEFT JOIN (Select pid, Sum(qty) as totstock from tblstocks group by pid) s ON s.pid=p.pid 
LEFT JOIN (Select pid, Sum(qty) as totsale from tbls group by pid) sl ON sl.pid=p.pid 

Sql Fiddle Demo

+0

谢谢先生!它现在得到正确的价值..我没有想法,我可以选择也在'左加入' – kashimu

+0

@ kashimu您的欢迎总是... –

+0

@Parado谢谢。 –

0

也试试p.product_name上的群组。我认为这将解决 问题。