如何在MySQL中优化涉及子选择的查询?

时间:2013-07-18 09:40:16

标签: mysql query-optimization

假设我有一个这样的表:

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

并且有一个连锁的主键,包括websitefromcitytocityroundtripdepdateretdate。没有其他索引。

解释说:

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

1 个答案:

答案 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;