为每个帖子选择最后三个评论者(每组最大n个)

时间:2015-01-18 19:40:52

标签: mysql sql select distinct greatest-n-per-group

的MySQL

SELECT DISTINCT comments.commenter_id FROM comments WHERE ((oid IN (421,425) 
AND otype = 'post') (oid IN (331) AND otype = 'photo')) ORDER BY  
post_id,type,comment_id LIMIT 3

我想要做的是为每个distinct commenterspost选择最后三个photo和各自的ID。 即每个o_ido_type组合最多3个评论者

但是上面而不是让我过去三distinct commenters让我产生total three。 我哪里错了?谁能帮助我?

IF LIMIT为2

ID | oid | otype | commenter_id
1    1      post    1
2    1      post    1
3    1      post    2
4    1      post    3
5    2      post    1
6    1      photo   2
7    2      post    3

输出应该

commenter_id| o_type | o_id
 3            post      1   
 2            post      1
 3            post      2
 1            post      2
 2            photo     1    

1 个答案:

答案 0 :(得分:1)

已解决 - 最大的每组N

虽然这很简单! :P

This question帮了我很多忙。

SELECT DISTINCT t.commenter_id,t.o_id,t.otype
from 
(
SELECT c.*,
    @row_number:=if(@post_id = oid, @row_number + 1, 1) AS row_number,
       @oid:=oid AS varval
FROM comments c
join (select @row_number := 0, @oid:= NULL) as var
    ON 
    ((oid IN (425) AND otype = 'post') OR (oid IN (331) AND otype = 'photo'))

order by comment_id DESC
) t
where t.row_number <=2