假设我有一个这样的表:
id | price | group1
1 | 6 | some_group
2 | 7 | some_group
3 | 8 | some_group
4 | 9 | some_other_group
如果我想选择按group1
我可以这样做:
SELECT id, min(price), group1 FROM some_table GROUP BY group1;
问题是,当我的表格没有按照这样的价格排序时:
id | price | group1
1 | 8 | some_group
2 | 7 | some_group
3 | 6 | some_group
4 | 9 | some_other_group
然后我的查询返回此结果集:
id | price | group1
1 | 6 | some_group
4 | 9 | some_other_group
问题是我在1
列中获得了id
,但id
行的6
的价格不是1
,而是3
{1}}。
我的问题是,当我使用GROUP BY
时,如何从包含最低价格的行中获取值?
我试过了:
SELECT f.id, min(f.price), f.group1 FROM (SELECT * FROM some_table ORDER BY price) f
GROUP BY f.group1;
但这真的很慢,如果我有多个列和聚合,它可能会失败。
请注意,上述名称仅用于演示目的。我的真实查询如下所示:
SELECT depdate, retdate, min(totalprice_eur) price FROM
(SELECT * FROM flight_results
WHERE (
fromcity = 30001350
AND tocity = 30001249
AND website = 80102118
AND roundtrip = 1
AND serviceclass = 1
AND depdate > date(now()))
ORDER BY totalprice_eur) F
WHERE (
fromcity = 30001350
AND tocity = 30001249
AND website = 80102118
AND roundtrip = 1
AND serviceclass = 1
AND depdate > date(now()))
GROUP BY depdate,retdate
并且有一个连锁的主键,包括website
,fromcity
,tocity
,roundtrip
,depdate
和retdate
。没有其他索引。
解释说:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 2837 Using where; Using temporary; Using filesort
2 DERIVED flight_results ALL PRIMARY NULL NULL NULL 998378 Using filesort
答案 0 :(得分:2)
您可以这样做:
SELECT t1.id, t1.price, t1.group1
FROM some_table AS t1
INNER JOIN
(
SELECT min(price) minprice, group1
FROM some_table
GROUP BY group1
) AS t2 ON t1.price = t2.minprice AND t1.group1 = t2.group1;