当我输入此查询时,
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。然而,我不知道如何摆脱这个问题并防止在第一个查询中返回重复的结果,如下所示。
附加架构:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
最佳答案
您需要使用 Orders
表从 OrderDetails
加入 Customers
,因为 OrderDetails
不不包含访问 customers
表所需的 customerid
。
更好的查询是:
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;
这里我们避免使用自然连接
,因为这些可能是不可预测的,并且在编写 SQL 时,尽可能明确总是一个好主意。此外,我们使用Orders
表来获取customers
的链接。
关于mysql - 为什么 SQL 返回太多结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40897037/