tags page_id
a     5
a     6
a     8
a     9
a     11
a     15
b     2
b     4
c     1
c     3 
c     12 
c     14
c     16
d     7
d     10
d     13
d     17如何group by,每个group获取3条记录,如果少于3条的,有多少条返回多少条记录。
另外我想要效率高点的语句,因为我总计有40万条记录,大概占了6500个group。是否还需要建立相应的索引?谢谢。a     5
a     6
a     8
b     2
b     4    
c     1
c     3 
c     12
d     7
d     10
d     13

解决方案 »

  1.   


    select tags ,page_id from 
    (
    select tags ,page_id,(select count(1) from tb_name where a.tags = tags and page_id <= a.page_id) rn
    from tb_name a
    ) t
    where t.rn<=3;
      

  2.   

    参考下贴中的多种方法http://blog.csdn.net/acmain_chm/article/details/4126306
    [征集]分组取最大N条记录方法征集,及散分....
      

  3.   

    select * from table1 t
    where 3>(select count(*) from table1 where tags=t.tags and page_id<t.page_id)
      

  4.   

    在tags, page_id上建立索引SELECT * from ttl a where 3>=(select count(*) from ttl where a.tags=tags and a.page_id>=page_id)or
    SELECT a.tags, a.page_id from ttl a left join ttl b on  a.tags=b.tags and a.page_id>=b.page_id
    group by a.tags, a.page_id
    having count(*)<=3