Postgresql 加入三个 table

Postgresql join three table

我有一个库存数据库,我需要通过我的库存计算每次买入或卖出操作后的产品数量。所以,我有三个 tables.The 等式是这样的:

(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 ; 

我的猜测是您需要求和并修复括号以便它们平衡:

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 通常会导致整个表达式 return NULL.

您也可以尝试显式连接:

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