MYSQL - 组合来自同一个表的多个查询

时间:2013-11-21 16:35:09

标签: 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

2 个答案:

答案 0 :(得分: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,但看看是否能给你你想要的东西。

答案 1 :(得分: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