我在 MySQL 销售数据库中有两个表:
订单表:
CREATE TABLE salestest.`orders` (
`ID` int(11) unsigned NOT NULL auto_increment,
`OrderDate` datetime NOT NULL,
`CustomerID` int(11) unsigned NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`),
KEY `OrderDate` (`OrderDate`),
KEY `CustomerID` (`CustomerID`)
) ENGINE=InnoDB;
INSERT INTO salestest.orders VALUES
( 1, '2012-04-15', 1 ),
( 2, '2012-05-20', 1 ),
( 3, '2012-06-30', 1 );
订单详情表:
CREATE TABLE salestest.`OrderDetails` (
`ID` int(11) unsigned NOT NULL auto_increment,
`OrderID` int(11) unsigned NOT NULL,
`ProductID` int(11) unsigned NOT NULL,
`Price` double NOT NULL default '0',
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`),
KEY `OrderID` (`OrderID`),
KEY `ProductID` (`ProductID`),
CONSTRAINT `OrderID_fk` FOREIGN KEY (`OrderID`) REFERENCES `orders` (`ID`)
) ENGINE=InnoDB;
INSERT INTO salestest.OrderDetails VALUES
( 1, 1, 1, 2 ),
( 2, 1, 2, 15 ),
( 3, 1, 3, 22 ),
( 4, 2, 1, 3 ),
( 5, 2, 2, 17 ),
( 6, 2, 3, 23 ),
( 7, 2, 4, 40 ),
( 8, 3, 1, 4 ),
( 9, 3, 2, 20 );
现在我需要为每个客户选择他们购买每种产品的最后价格。
最简单的方法是使用子查询:
SELECT od2.CustomerID,od2.ProductID, od2.Price AS LastPrice, od2.OrderDate AS LastDate
FROM (SELECT o1.ID, o1.CustomerID, o1.OrderDate, od1.ProductID, od1.Price
FROM orders AS o1
LEFT JOIN OrderDetails as od1 ON o1.ID=od1.OrderID
ORDER BY OrderDate DESC) AS od2
GROUP BY CustomerID, ProductID
ORDER BY CustomerID, ProductID;
结果:
CustomerID ProductID LastPrice LastDate
1 1 4 2012-06-30 00:00:00
1 2 20 2012-06-30 00:00:00
1 3 23 2012-05-20 00:00:00
1 4 40 2012-05- 20 00:00:00
现在的问题;如果我想避免子查询、临时表或视图,怎么可能得到相同的结果,我只想使用连接;这个查询是一个更大查询的一小部分,并且有子查询是非常低效的。
我试过这个查询:
SELECT o1.CustomerID,od1.ProductID, od1.Price AS LastPrice, o1.OrderDate AS LastDate
FROM Orders AS o1 LEFT JOIN OrderDetails as od1 ON o1.ID=od1.OrderID
GROUP BY CustomerID, ProductID
ORDER BY CustomerID, ProductID;
但它给出了不同的结果:
CustomerID ProductID LastPrice LastDate
1 1 2 2012-04-15 00:00:00
1 2 15 2012-04-15 00:00:00
1 3 22 2012-04-15 00:00:00
1 4 40 2012-05- 20 00:00:00
如您所见, LastPrice 和 LastDate 不正确。我也尝试了艾伦的建议,但结果是:
CustomerID ProductID LastPrice LastDate
1 1 4 2012-06-30 00:00:00
1 2 20 2012-06-30 00:00:00
斯宾塞的回答结果中的第一个查询重复的产品:
CustomerID ProductID LastPrice LastDate
1 3 22 2012-04-15 00:00:00
1 3 23 2012-05-20 00:00:00
1 4 40 2012-05-20 00:00:00
1 1 4 2012-06- 30 00:00:00
1 2 20 2012-06-30 00:00:00
其他答案都使用子查询,我试图避免。
有什么建议么?