应用场景大概是这样的:比如有很多消息流,这些消息来自不通的app,聚合在一个页面上,查看的时候不能让一个app的消息霸屏,所以就会类似于折叠功能,同一个app的消息只显示最多5条,再多的话,就要点进去看。这样整个首页上就可以看到很多app的消息,整体还是按照时间先后,但是某一个app连续的消息不会超过5条,可以出现a1,a2,a3,a4,a5,b1,b2,b3,b4,a6,a7这样间隔出现,但是连续的a只会最多出现5条。11年后重建了一次现场,数据如下:
执行 select a.msg_id, a.app_id, a.ctime from user_request as a where 3> (select count(*) from user_request where app_id = a.app_id and msg_id > a.msg_id) order by ctime desc;
以上为2022年12月5日补充
-----------------------------------------------------------------------------------------------------------------------------
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 <= 4 order by a.msg_id desc ) `temp` where rank >2 and rank <=4;
上面实现取第3到第4组,每组5条记录,按时间排序
这只是单纯DB实现,在实际应用中,对于这样耗时的DB操作应当尽量避免,最好将数据cache出来,在逻辑层做这种复杂操作