MS Access SQL中的相关子查询结构

时间:2017-10-25 00:36:02

标签: sql ms-access subquery

我关闭了,但我似乎无法弄清楚这个SQL查询。我已经获得了SELECT和相关的FROM表,但我认为我的子查询结构搞砸了。

问题:撰写SQL语句以生成每种原材料的两个最便宜的供应商(供应商)的列表。在结果表中,显示以下列:物料ID,物料描述,供应商ID,供应商名称和供应商的单价。按物料ID和供应商的单价按升序对结果表进行排序。注意:如果原材料只有一个供应商(供应商),那么该供应商及其原材料的单价也应该在结果(输出)表中。

以下是我所拥有的:

SELECT Supplies_t.Material_ID, Raw_Materials_t.Material_Description, 
Vendor_t.Vendor_ID, Vendor_t.Vendor_name, Supplies_t.Unit_price
FROM Supplies_t S1, Raw_Materials_t, Vendor_t
WHERE Vendor_t.Vendor_ID = Supplies_t.Vendor_ID
AND Supplies_t.Material_ID = Raw_Materials_t.Material_ID
AND Supplies_t.Unit_price IN
  (SELECT TOP 2 Unit_price
  FROM Supplies_t S2
  WHERE S1.Material_ID = S2.Material_ID
  ORDER BY S2.Material_ID ASC, S2.Unit_price ASC)

1 个答案:

答案 0 :(得分:0)

使用正确的表别名可以解决您的问题。您还应该使用显式JOIN语法:

SELECT s.Material_ID, rm.Material_Description, v.Vendor_ID, v.Vendor_name, s.Unit_price
FROM (Supplies_t s INNER JOIN
      Raw_Materials_t rm
      ON s.Material_ID = rm.Material_ID
     ) INNER JOIN
     Vendor_t v
     ON v.Vendor_ID = s.Vendor_ID
WHERE s.Unit_price IN (SELECT TOP 2 s2.Unit_price
                       FROM Supplies_t s2
                       WHERE s.Material_ID = s2.Material_ID
                       ORDER BY s2.Material_ID ASC, s2.Unit_price ASC
                      );