2015-01-31 95 views
0

我有2個表格。一個是「收貨」表。另一個是「product_use_for」表。2表數據總和並按產品名稱顯示訂單

我需要sum(goods_receive.quantity)和sum(product_use_for.quentity) 並按產品名稱顯示順序。

其實我是新的php.I混淆這個問題。如果有人幫助我,我會很開心。請。

請參閱此圖像>>

enter image description here

+0

$ SQL = 「SELECT goods_receive.p_name,總和(goods_receive.quantity)作爲QUA,總和(product_use_for.quantity)作爲use_qua FROM goods_receive,product_use_for BY goods_receive.p_name GROUP」; – 2015-01-31 22:08:34

回答

0

您需要使用LEFT JOIN,這樣你會得到行的結果,即使有在product_use_for表中沒有匹配。而且你需要在子查詢中完成其中一個和數,否則你將把總和乘以另一個表中的行數。

SELECT gr.p_name AS product_name, SUM(gr.quantity) AS stock_quantity, IFNULL(puf.quantity, 0) AS use_quantity 
FROM goods_receive AS gr 
LEFT JOIN (SELECT p_name, SUM(quantity) AS quantity 
      FROM product_use_for 
      GROUP BY p_name) AS puf 
ON gr.p_name = puf.p_name 
GROUP BY gr.p_name 

DEMO

+0

很多感謝兄弟..問題解決。 – 2015-01-31 22:25:47

相關問題