Home >Database >Mysql Tutorial >mysql实现每组取前N条记录的sql,以及后续的组数据量限制

mysql实现每组取前N条记录的sql,以及后续的组数据量限制

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 15:53:04882browse

select a.msg_id, a.com_id, a.data, a.ctime from sns_user_03.user_request_86 a where 5 (select count(*) from sns_user_03.user_request_86 where uid=8880386 and com_id = a.app_id and msg_id a.msg_id ) order by a.ctime; 上面的sql实现分组查询,

select a.msg_id, a.com_id, a.data, a.ctime from sns_user_03.user_request_86 a where 5 > (select count(*) from sns_user_03.user_request_86 where uid=8880386 and com_id= a.app_id and msg_id > a.msg_id ) order by a.ctime;

 

 

上面的sql实现分组查询,每组最多显示5条记录,按照时间排序

 

 

select @rank:=0;

select msg_id, app_id, data, ctime, rank from ( select a.msg_id, a.app_id, a.data, a.ctime, if(@appid!=a.app_id,@rank:=@rank+1,@rank:=@rank) as rank, @appid:=a.app_id from sns_user_03.user_request_86 a where 5 > (select count(*) from sns_user_03.user_request_86 where uid=8880386 and app_id = a.app_id and msg_id > a.msg_id ) and @rank 2 and rank

 

上面实现取第3到第4组,每组5条记录,按时间排序

 

 

这只是单纯DB实现,在实际应用中,对于这样耗时的DB操作应当尽量避免,最好将数据cache出来,在逻辑层做这种复杂操作

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn