2013-08-01 108 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上的羣組。我認爲這將解決 問題。