SQL多个INNER加入一个Select-Statement

时间:2018-02-08 10:42:38

标签: sql vb.net ms-access

我正在使用此代码进行库存管理系统,其中我想从四个表中检索库存。我已经尝试了两张桌子并且得到了准确的结果,因为我需要它。请帮助我。

表架构

Productmastertb

prod_id,
Product_name

salesdetailstb

sales_id,
Prod_id,
Prod_qty

estimatedetailstb

est_id,
Prod_id,
Prod_qty

Purchasedetailstb

est_id,
Prod_id,
Prod_qty

查询示例(工作):

SELECT
    productmastertb.prod_id, 
    productmastertb.prod_name, 
    sum(estimatedetailstd.prod_qty) as Est_qty 
FROM 
    productmaster 
INNER JOIN 
    estimatedetailstb ON productmastertb.prodid = estimatedetails.prodid 
GROUP BY 
    productmastertb.prod_id, productmastertb.prod_name

同样,我必须检索salesdetailstb.qty和purchasedetailstb.qty的总和

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以添加多个联接。

SELECT t1.id, t4.name, count(t4.name) 
FROM Table1 AS t1
    INNER JOIN Table2 AS t2 -- the AS statement renames the table within
                            -- this query to t2. Columns from this table can be used 
                            -- as t2.columnname. This needs to be done when you have 
                            -- columns with the same name in different tables.
        ON t1.id = t2.id
    INNER JOIN Table3 as t3
        ON t1.id = t3.id
    INNER JOIN Table4 as t4
        ON t3.name = t4.name
GROUP BY t1.id, t4.name 

答案 1 :(得分:0)

您想要总结不同的"维度" - 那就是桌子。一个好的方法是在执行JOIN之前聚合。或者使用子查询。以下是后一种方法:

SELECT pm.prod_id, pm.prod_name, 
       (SELECT SUM(ed.prod_qty)
        FROM estimatedetailstb as ed
        WHERE ed.prodid = ed.prodidas
       ) as Est_qty,
       (SELECT SUM(sd.prod_qty)
        FROM salesdetailstb as sd
        WHERE sd.prodid = pm.prodidas
       ) as Sales_qty,
       (SELECT SUM(pd.prod_qty)
        FROM purchasedetailstb as pd
        WHERE pd.prodid = pm.prodid
       ) as Sales_qty
FROM productmaster pm;

这将为您提供所有产品,甚至包括一个或多个其他表中缺少的产品。