2

我正在像这样从用户活动表中检索行

SELECT user_id, type, source_id FROM activity ORDER BY date DESC LIMIT 5

但是我不希望活动源能够被同一个用户阻塞,所以我希望能够在 5 行中检索最多 3 行包含相同的 user_id。

任何想法我怎么能做到这一点?谢谢 :)

4

2 回答 2

1

这是一种“传统”方式,您首先枚举用户 id 并将此信息用作过滤器:

SELECT user_id, type, source_id
FROM (select a.*,
             @rn := if (@user_id = user_id, @rn + 1, 1) as rn,
             @user_id := user_id
      from activity a cross join
           (select @rn := 0, @user_id := -1) const
      order by user_id
     ) a
WHERE rn <= 3
ORDER BY date DESC
LIMIT 5;
于 2013-08-17T11:16:45.740 回答
1

你可以试试这个: -

SELECT user_id, type, source_id
FROM activity
WHERE 3 > (
SELECT count( * )
FROM activity AS activity1
WHERE activity .user_id = activity1.user_id
AND activity.user_id > activity1.user_id)
ORDER BY activity.user_id DESC
LIMIT 5
于 2013-08-17T11:18:07.197 回答