2

我有一个关系数据库架构,如下所示: 在此处输入图像描述

问题是“查找在 2009 年购买产品且产品由霍尼韦尔于 1968 年制造的客户的详细信息”。

到目前为止我所做的是:

SELECT * FROM Customer
WHERE CID IN
    (SELECT Customer_ID FROM Order
     WHERE Purchase_Date = 2009 
     AND EXISTS
        (SELECT * FROM Order_Items, Product, Manufacturer
         WHERE OID = OID AND Product_ID = PID AND MID = Manufacturer_ID AND
         Mnufacturer_Name = "Honeywell" AND Manufacturerd_Date = 1968));

我研究数据库才大约一个月,所以我想这里的专家看起来会很复杂..我做对了吗?否则,请提供任何反馈在哪里修复..

提前致谢。

4

1 回答 1

2

通常,当从关系数据库中的相关表中检索信息时,您应该JOIN使用适合从查询中获得的结果的连接类型的表。是否包括外部表中不匹配的行。因此,在您的情况下,您可以这样做:

SELECT DISTINCT c.*
FROM Customer c
INNER JOIN Order        o ON c.CID             = o.Customer_ID
INNER JOIN OrderItems  oi ON o.OID             = oi.OID
INNER JOIN Product      p ON oi.ProductID      = p.PID
INNER JOIN Manufacturer m ON p.Manufacturer_ID = m.MID
WHERE o.Purchase_Date = 2009 
  AND m.Mnufacturer_Name = "Honeywell"
  AND m.Manufacturerd_Date = 1968

但是,在您发布的查询中:

SELECT * FROM Customer
WHERE CID IN
    (SELECT Customer_ID FROM Order
     WHERE Purchase_Date = 2009 
     AND EXISTS
        (SELECT * FROM Order_Items, Product, Manufacturer
         WHERE OID = OID AND Product_ID = PID AND MID = Manufacturer_ID AND
         Mnufacturer_Name = "Honeywell" AND Manufacturerd_Date = 1968));

您正在使用IN谓词并连接三个表Order_ItemsProductManufacturer使用旧的连接语法.. FROM Order_Items, Product, Manufacturer WHERE OID = OID AND Product_ID = PID AND MID = Manufacturer_ID

您的查询可能有效。但是,如果有任何NULL值,Customer_ID则它不会返回任何结果。但它会更容易使用JOIN。这是一个有用的赞JOIN

于 2012-11-01T08:46:25.777 回答