SQL:返回最近的操作,但限制为10个结果

时间:2011-12-21 17:11:35

标签: mysql group-by limit

我有一张表,其中包含演员执行的操作,并希望返回最近的10个操作。我希望演员在这个列表中是独一无二的。 'created'是时间/日期标记。我怎样才能最有效地完成这项工作?我想出了以下查询,其中有效:

SELECT * 
FROM activities a
JOIN 
(SELECT actor, MAX(created) created 
 FROM activities 
 WHERE comment_type <> 'profile.status' 
 GROUP BY actor) t ON (a.actor = t.actor AND a.created = t.created) LIMIT 10

该表最终可能会非常大。

2 个答案:

答案 0 :(得分:0)

您可以将限制10放在子查询中 除此之外看起来还不错

SELECT * FROM activities a
INNER JOIN (
            SELECT 
              actor
              , MAX(created) created 
            FROM activities 
            WHERE comment_type <> 'profile.status' 
            GROUP BY actor
            LIMIT 10 OFFSET 0) t
      ON (a.actor = t.actor AND a.created = t.created) LIMIT 10

答案 1 :(得分:0)

如果你只需要演员,你可以这样做

SELECT DISTINCT actor -- and any other actor specific columns that are unique to the actor
FROM activities 
WHERE comment_type <> 'profile.status'
ORDER BY Created DESC
LIMIT 10