2011-12-21 82 views
0

我有一個表,其中有由角色執行的操作並希望返回最近操作的10個操作。我希望演員在這個列表中是唯一的。 '創建'是時間/日期戳記。我怎樣才能最有效地做到這一點?我想出了以下查詢,它可以工作:SQL:返回最近的操作,但限制爲10個結果

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 

該表最終可能會相當大。

回答

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 
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