您可能需要使用派生表,如下所示:
SELECT o1.item_id, o1.max_price, o2.user_id user_of_max_price
FROM (
SELECT item_id, MAX(price) max_price
FROM `order`
GROUP BY item_id
) o1
JOIN `order` o2 ON (o2.price = o1.max_price AND o2.item_id = o1.item_id)
GROUP BY o1.item_id;
測試用例:
CREATE TABLE `order` (user_id int, item_id int, price decimal(5,2));
INSERT INTO `order` VALUES (1, 1, 10);
INSERT INTO `order` VALUES (1, 2, 15);
INSERT INTO `order` VALUES (1, 3, 8);
INSERT INTO `order` VALUES (2, 1, 20);
INSERT INTO `order` VALUES (2, 2, 6);
INSERT INTO `order` VALUES (2, 3, 15);
INSERT INTO `order` VALUES (3, 1, 18);
INSERT INTO `order` VALUES (3, 2, 13);
INSERT INTO `order` VALUES (3, 3, 10);
結果:
+---------+-----------+-------------------+
| item_id | max_price | user_of_max_price |
+---------+-----------+-------------------+
| 1 | 20.00 | 2 |
| 2 | 15.00 | 1 |
| 3 | 15.00 | 2 |
+---------+-----------+-------------------+
3 rows in set (0.00 sec)
它工作完美。謝謝,丹尼爾! – Ohas 2010-08-28 11:53:15