我有一个库存数据库,我需要通过我的库存计算每次买入或卖出操作后的产品数量。所以,我有三张桌子。等式是这样的:
(QtyInital + (BuyQuantity(IN) - SELLQUANTITY(OUT)
这是我的三张桌子的架构。
product(pid,name,qteInital,qteStock);
productInBuyFacture(baid,pid,qte,price,subtotal);
productInSellFacture(bsid,pid,qte,price,subtotal);
我想通过触发器计算当前的库存数量。我尝试通过SUB QUERYIES这样做,
select ((select qteInital from product where id = 3) +
(select qte from productInBuyFacture where pid = 3 ) -
(select qte from productInSellFacture where pid = 3) as currentQuantity ;
答案 0 :(得分:1)
我的猜测是你需要求和并修正括号以便它们平衡:
select ((select coalesce(sum(qteInital), 0) from product where id = 3) +
(select coalesce(sum(qte), 0) from productInBuyFacture where pid = 3 ) -
(select coalesce(sum(qte), 0) from productInSellFacture where pid = 3)
) as currentQuantity ;
coalesce()
是为了防止不匹配问题。算术表达式中的NULL
通常会导致整个表达式返回NULL
。
答案 1 :(得分:1)
您也可以尝试使用显式连接:
SELECT pro.pid, pro.QtyInital, COALESCE(SUM(buy.qte), 0) AS buyqty, COALESCE(SUM(sell.qte), 0) AS sellqty
FROM product AS pro
LEFT JOIN productInBuyFacture AS buy
ON pro.pid = buy.pid
LEFT JOIN productInSellFacture AS sell
ON pro.pid = sell.pid
GROUP BY pro.pid, pro.QtyInital