SQL查询显示4x记录

时间:2013-01-07 20:04:35

标签: sql select

以下声明正常运行但每次显示4次。重复;我知道这种关系是错误的,但不知道如何修复它?抱歉,如果这很简单,我就错过了。

SELECT Customers.First_Name, Customers.Last_Name, Plants.Common_Name, Plants.Flower_Colour, Plants.Flowering_Season, Staff.First_Name, Staff.Last_Name
FROM Customers, Plants, Orders, Staff
INNER JOIN Orders AS t2 ON t2.Order_ID = Staff.Order_ID
WHERE Orders.Order_Date
BETWEEN  '2011/01/01'
AND  '2013/03/01'

3 个答案:

答案 0 :(得分:6)

您正在表之间生成笛卡尔积,因为您没有在任何表之间提供连接语法:

SELECT c.First_Name, c.Last_Name, 
    p.Common_Name, p.Flower_Colour, p.Flowering_Season, 
    s.First_Name, s.Last_Name
FROM Customers c
INNER JOIN Orders o
    on c.customerId = o.customer_id 
INNER JOIN  Plants p
    on o.plant_id = p.plant_id
INNER JOIN Staff s
    ON o.Order_ID = s.Order_ID
WHERE o.Order_Date BETWEEN  '2011/01/01' AND  '2013/03/01'

注意:我在猜测连接的列名

这是一个很棒的visual explanation of joins,有助于学习正确的语法

答案 1 :(得分:2)

FROM...条款中,您正在进行交叉联接 - 将每个客户与每个工厂相结合,每个订单都与每个员工相结合。

您只应在FROM子句中提及一个表,然后将其他表连接到INNER JOINS以仅获取相关记录。

我不确切知道你的数据库是怎么样的,但是像这样:

SELECT Customers.First_Name, Customers.Last_Name, Plants.Common_Name,
Plants.Flower_Colour, Plants.Flowering_Season, Staff.First_Name, Staff.Last_Name
FROM Customers
INNER JOIN Orders ON Orders.Customer_ID = Customers.Customer_ID
INNER JOIN Staff ON Staff.Staff_ID = Orders.Staff_ID
INNER JOIN Plants ON Plants.Plants_ID = Orders.Plants_ID
WHERE Orders.Order_Date
BETWEEN  '2011/01/01'
AND  '2013/03/01'

答案 2 :(得分:2)

这是因为您从四个表中进行选择而没有任何连接,并且还因为您要加入Orders两次。结果,制作了笛卡尔积

以下是修复方法:使用ANSI语法重写theta连接,并提供正确的连接条件:

SELECT Customers.First_Name, Customers.Last_Name, Plants.Common_Name, Plants.Flower_Colour, Plants.Flowering_Season, Staff.First_Name, Staff.Last_Name
FROM Customers
JOIN Plants ON ...
JOIN Orders ON ...
JOIN Staff ON ...
INNER JOIN Orders AS t2 ON t2.Order_ID = Staff.Order_ID
WHERE Orders.Order_Date BETWEEN  '2011/01/01' AND  '2013/03/01'

用适当的连接条件替换...;这应该使结果看起来像预期的那样。