The combination of limit and paging in SQL

select * from test limit 2,10;

The meaning of this statement: Starting from the 3 statement, a total of 10< is displayed /span> statements.

select * from test limit a,b;

a=0, the first record.

a=1, the second record.

a=2, the third record. 

The meaning of this statement: Start querying from the a+1 statement, showing a total of b statements. 

If there are totalRecord_num pieces of data, you want to display them in pages ,

There are rnpp pieces of data per page, totaling page_num pages, and the number of records on the last page is lprn.

Record_num=page_num*rnpp+lprn;

Known Record_num,rnpp.

lprn=Record_num%rnpp;
if(lprn==0){page_num=Record_num/rnpp;}
else {page_num=Record_num/rnpp+1;}

Now I want to get the corresponding data of page now_page. How to use SQL to express it?

think:

Which record does the corresponding data start from, and how many are there in total?

Assume that the corresponding data starts from record c, and there are b records in total.

The first piece of data on the first page: c=1

The first piece of data on the second page: c=1+rnpp;

The first piece of data on the third page: c=1+rnpp*2;

The first piece of data on page now_page: c=1+rnpp*(now_page-1);

How much data is there in page now_page?

Discuss on a case-by-case basis:

(1)lprn=0, that is, each page has rnpp pieces of data.

(2)lprn!=0, the first page_num-1 pages have rnpp data, and the last page of data is lprn.

if(lprn==0)b=rnpp;
else{
    if(now_page==page_num)b=lprn;
    else b=rnpp;
}

The final relevant SQL statement:

a=c-1;
select * from test limit a,b;

 

Guess you like

Origin blog.csdn.net/weixin_51883798/article/details/134730807