为什么SQL返回太多结果?

时间:2016-11-30 19:55:34

标签: mysql join

当我输入此查询时,

SELECT OrderDetails.OrderDetailID, Customers.CustomerName
  FROM OrderDetails, Customers 
       NATURAL JOIN Products
       NATURAL JOIN Customers
WHERE SupplierID = 5;

返回1001条记录。

当我输入此查询时,

SELECT OrderDetailID
  FROM OrderDetails 
       NATURAL JOIN Products
WHERE SupplierID = 5;

返回11条记录

正如您所料,Customer表中有91条记录,第二条查询中返回了11条结果,91 * 11 = 1001。我不知道如何摆脱这种情况,并防止在第一个查询中返回重复的结果,如此。

Duplicate Returns

架构附件:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

2 个答案:

答案 0 :(得分:0)

您需要使用Orders表加入Customers中的OrderDetails,因为OrderDetails不包含所需的customerid为了你到达customers表。

更好的查询是:

    SELECT orderDetails.OrderDetailID, customers.CustomerName
    FROM OrderDetails orderDetails
        INNER JOIN Orders orders on orderDetails.OrderID = orders.OrderID
        INNER JOIN Customers customers on orders.customerID = customers.customerID
        INNER JOIN Products products on prderDetails.ProductID = products.ProductID
    WHERE products.SupplierID = 5;

这里我们避免使用Natural Joins,因为那些是不可预测的,在编写SQL时,最好尽可能明确。此外,我们使用Orders表来获取customers的链接。

答案 1 :(得分:0)

将逗号(CROSS JOIN的简写)替换为另一个NATURAL JOIN。此外,使用NATURAL JOIN时,您不需要使用范围变量,即将OrderDetails.OrderDetailID更改为OrderDetailID

SELECT OrderDetailID, CustomerName
  FROM OrderDetails
       NATURAL JOIN Orders
       NATURAL JOIN Customers
       NATURAL JOIN Products
 WHERE SupplierID = 5;