Mysql implements the SQL statements for getting the first N records for each group and the subsequent group data volume restrictions.

Source: Internet
Author: User
Selecta. msg_id, a.com _ id, a. data, a. ctimefromsns_user_03.user_request_86awhere5 (selectcount (*) timeout) orderbya. ctime; the preceding SQL statement implements group query,

Select. msg_id, a.com _ id,. data,. 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 =. app_id and msg_id. msg_id) order by. ctime; the preceding SQL statement implements grouping query,

Select. msg_id, a.com _ id,. data,. 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 =. app_id and msg_id>. msg_id) order by. ctime;

In the preceding SQL grouping query, each group can display up to five records, sorted by Time

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! =. App_id, @ rank: = @ rank + 1, @ rank: = @ rank) as rank, @ appid: =. 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 =. app_id and msg_id>. msg_id) and @ rank <= 4 order by. msg_id desc) 'temp 'where rank> 2 and rank <= 4;

In the preceding example, 3rd to 4th groups are obtained, with 5 Records in each group sorted by time.

This is only a pure DB implementation. In practical applications, we should avoid such time-consuming DB operations as much as possible. It is best to cache the data and perform such complex operations at the logic layer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.