Postgresql联接三表
我有一个库存数据库,我需要通过我的库存计算每次买卖操作后的产品数量。我有三张表,方程如下:Postgresql联接三表,postgresql,subquery,Postgresql,Subquery,我有一个库存数据库,我需要通过我的库存计算每次买卖操作后的产品数量。我有三张表,方程如下: (QtyInital + (BuyQuantity(IN) - SELLQUANTITY(OUT) 这是我的三个表的模式 product(pid,name,qteInital,qteStock); productInBuyFacture(baid,pid,qte,price,subtotal); productInSellFacture(bsid,pid,qte,price,subtotal
(QtyInital + (BuyQuantity(IN) - SELLQUANTITY(OUT)
这是我的三个表的模式
product(pid,name,qteInital,qteStock);
productInBuyFacture(baid,pid,qte,price,subtotal);
productInSellFacture(bsid,pid,qte,price,subtotal);
我想通过触发器计算当前的库存量。我试着通过这样的子查询
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
通常会导致整个表达式返回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
当你试着那样做的时候发生了什么?