mysql實現每組取前N條記錄的sql,以及後續的組資料量限制

來源:互聯網
上載者:User

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出來,在邏輯層做這種複雜操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.