试图获得:

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

最佳答案

您在那里有两个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,但是请查看它是否能满足您的需求。

关于mysql - MYSQL-合并来自同一表的多个查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20126689/

10-12 14:36