2013-11-21 81 views
0

組合多個查詢好一會:MYSQL - 來自同一個表

trans_id | qty | ptotal 
--------------------------- 
100  | 30 | 2 
101  | 25 | 0 
從INV表

trans_id | pull_from_trans | trans_desc | qty | itc_part_id 
--------------------------------------------------------------- 
100  | null   | rec  | 30 | 1003 
101  | null   | rec  | 25 | 1010 
102  | 100    | pull  | 1 | 1003 
103  | 100    | pull  | 1 | 1003   

使用

(但不工作)

SELECT tb1.trans_id, tb1.qty,sum(tb2.qty) as ptotal 
FROM inv tb1 where tb1.trans_desc='rec' 
    INNER JOIN inv tb2 ON tb1.trans_id=tb2.pull_from_trans 
WHERE tb2.trans_desc='pull' GROUP BY tb2.pull_from_trans 

回答

0

你有兩個where子句那裏。將第一個驗證作爲AND添加到最終的WHERE子句中:

SELECT tb1.trans_id, tb1.qty, sum(tb2.qty) AS ptotal 
FROM inv tb1 
INNER JOIN inv tb2 ON tb1.trans_id = tb2.pull_from_trans 
WHERE tb2.trans_desc = 'pull' AND tb1.trans_desc = 'rec' 
GROUP BY tb2.pull_from_trans 

對您的GROUP BY不太確定。我可能會這樣做:GROUP BY tb1.trans_id, tb1.qty,如果你要求tb1.qty,但看看是否給你你想要的。

+0

這工作時,有沒有通過「pull_from_trans」鏈接的任何「拉」的交易除外。在例101中25 | 0不顯示在結果中。我嘗試了IFNULL(sum(tb2.qty),0),如下所示,但我得到了相同的結果。 – user3018316

+0

嘗試使用LEFT JOIN而不是INNER JOIN。 –

0

我不確定你到底在做什麼,但是下面的查詢會給出你需要的輸出。

SELECT tb1.trans_id, tb1.qty, IFNULL(sum(tb2.qty),0) AS ptotal 
FROM inv tb1 
LEFT JOIN inv tb2 ON tb1.trans_id = tb2.pull_from_trans 
WHERE tb2.trans_desc = 'pull' OR tb1.trans_desc = 'rec' 
GROUP BY tb1.trans_id 

SQL在這裏小提琴。

http://www.sqlfiddle.com/#!2/2acb5a/7