如何通过order by优化mysql组

时间:2014-06-24 15:47:33

标签: mysql sql group-by sql-order-by

当使用group by和order by时,我目前遇到极慢的查询。我倾向于没有使用索引,因为group by在一个单独的列上,然后按

排序

sqlFiddle

Foo表结构

id -> pk (indexed)
bar_id -> foreign key (indexed)
data -> varchar 
created_at -> timestamp (indexed)

以下是查询:

SELECT * FROM foo GROUP BY bar_id ORDER BY created_at DESC

我基本上试图获取每个bar_id的最新记录。然而,这需要11秒才能完成。有没有更好的方法来进行这种类型的查询?

1 个答案:

答案 0 :(得分:2)

SELECT COUNT(*) FROM foo;
+----------+
| COUNT(*) |
+----------+
|    98304 |
+----------+
1 row in set (0.03 sec)

SELECT x.* 
  FROM foo x
  JOIN
     ( SELECT bar_id
            , MAX(created_at) max_created_at 
         FROM foo
        GROUP
           BY bar_id
     ) y
    ON y.bar_id = x.bar_id 
   AND y.max_created_at = x.created_at;

531 rows in set (0.01 sec)

注意:我已略微修改了您的架构。 http://sqlfiddle.com/#!2/a6296/2