我在数据库中有两个名为purchase
和sales
的表
表格如下
表purchases
----------------------------
ID PRODUCT QTY
----------------------------
1 APPLE 100
2 BANANA 200
3 GRAPES 150
4 AVACADO 110
表Sales
----------------------------
ID PRODUCT QTY
----------------------------
1 APPLE 50
2 BANANA 200
3 GRAPES 100
在上面的表格中我有purchase
和sales
我希望从purchases
数量减去sales
数量
并获得像这样的输出
Output
----------------------------
ID PRODUCT QTY
----------------------------
1 APPLE 50
2 BANANA 0
3 GRAPES 50
4 AVACADO 110
我写了查询但没有工作
select id, product, (purchases.qty)-(sales.qty) from purchases left join sales on purchases.id=sales.id
答案 0 :(得分:1)
<强>解决方案强>
SELECT purchases.id,purchases.product, (purchases.qty - IF (sales.qty IS NULL, 0, sales.qty)) as qty FROM pruchases LEFT JOIN sales ON purchases.product = sales.product
答案 1 :(得分:0)