时间:2021-07-01 10:21:17 帮助过:32人阅读
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 <= 4 order by a.msg_id desc ) `temp` where rank >2 and rank <=4;
上面实现取第3到第4组,每组5条记录,按时间排序
这只是单纯DB实现,在实际应用中,对于这样耗时的DB操作应当尽量避免,最好将数据cache出来,在逻辑层做这种复杂操作