我有這樣的查詢,併成功獲取了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
但是當我試圖加入我的第二個表它得到錯誤的總totstock
和totsales
我有這個疑問,但我認爲它是錯誤的
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
'totstock'和'totsales'不僅僅是我想要的結果。我想一倍或三倍 – kashimu