日期:2014-05-16  浏览次数:20752 次

mysql group by每个group返回3条记录。
SQL code
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。是否还需要建立相应的索引?谢谢。

SQL code
a     5
a     6
a     8
b     2
b     4    
c     1
c     3 
c     12
d     7
d     10
d     13


------解决方案--------------------
SQL code

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;

------解决方案--------------------
SQL code
select * from table1 t
where 3>(select count(*) from table1 where tags=t.tags and page_id<t.page_id)

------解决方案--------------------


在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