我有三个桌子
表1:项目
id item
5 pen
6 pencil
表2:购买
id item qty item_id
1 pen 10 5
2 pencil 10 6
3 pen 10 5
表3:销售
id item qty item_id
1 pen 5 5
我想要的结果如下:
必填结果:
item purchase sale stock
pen 20 5 15
pencil 10 0 10
答案 0 :(得分:0)
您可以在下面的查询中尝试-
SELECT P.item, P.purchase, IFNULL(S.sale, 0), P.purchase - IFNULL(S.sale, 0) stock
FROM (SELECT item, SUM(qty) purchase
FROM purchase
GROUP BY item) P
LEFT JOIN (SELECT item, SUM(qty) sale
FROM sale
GROUP BY item) S ON P.item = S.item