更正db的mysql查询

时间:2013-11-28 18:22:31

标签: mysql sql

我有db和这样的表

CREATE TABLE OrderDetails(
    OrderID int NOT NULL,
    ProductID int NOT NULL,
    UnitPrice double NOT NULL  DEFAULT '0',
    Quantity smallint(6) NOT NULL DEFAULT '1',
    Discount double NOT NULL  DEFAULT '0',
    foreign key (OrderID) references Orders (OrderID),
    foreign key (ProductID) references Products (ProductID)
    );

还有另一个名为Orders的表,其中有1000行 也在projecttable我只有1000行

我有这样的疑问

INSERT INTO OrderDetails(OrderID,ProductID,UnitPrice,Quantity,Discount)
    SELECT OrderID, ProductID, OrdDetUnitPrice, OrdDetQuantity, OrdDetDiscount
    FROM (SELECT OrdDetUnitPrice, OrdDetQuantity, OrdDetDiscount, ProdProductName, CustCompanyName, EmpFirstName, EmpLastName FROM test.projecttable) as pt INNER JOIN
            (SELECT ProductID, ProductName FROM Products) as p ON p.ProductName=pt.ProdProductName INNER JOIN
                (SELECT LastName, FirstName, EmpId FROM Employees ) as e ON pt.EmpLastName=e.LastName AND pt.EmpFirstName=e.FirstName INNER JOIN
                    (SELECT CustID, CompanyName FROM Customer) as c ON pt.CustCompanyName=c.CompanyName INNER JOIN
                            (SELECT OrderID, CustID, EmpID FROM Orders) as o ON c.CustID=o.CustID AND e.EmpID=o.EmpID;

Coudl有人告诉我为什么如果Orders表中只有1000个,它会返回4084行

1 个答案:

答案 0 :(得分:0)

因为当你进行内部连接时,每次一侧的值与另一侧的值匹配时,它会返回一行。比如订单表中的第一行,有一个客户,一个员工,但有4个产品。所以如果我不得不猜测,我会说你的系统平均每个订单大约有4.084个产品。

我认为这是正确的答案。为什么您认为订单明细表中应该只有1000行?