Four usages of mysql database limit


foreword

The limit clause in the mysql database can be used to force the select statement to return a specified number of records. limit accepts one or two numeric arguments. The argument must be an integer constant. If two parameters are given, the first parameter specifies the offset of the first returned record line, and the second parameter specifies the maximum number of returned record lines; if one parameter is given, it indicates the maximum number of returned record lines .

1. Grammar

limit [offset] rows

2. Parameter description

offset:指定第一个返回记录行的偏移量(即从哪一行开始返回)。
注意:初始行的偏移量为0rows:返回具体行数。

3. Common examples - 4 usages

Create the t_user table and insert 10 pieces of test data, as shown in the figure below.
insert image description here

Usage 1: Starting from the third item, retrieve 5 items of data (the offset offset starts from offset+1)

select * from t_user limit 2,5;

insert image description here

Usage 2: Take 5 pieces of data from the first piece (only one parameter rows)

select * from t_user limit 5;

insert image description here

Usage 3: Implement paging function

select * from table t_user (currentPage-1)*pageSize,pageSize;

Parameter currentPage: Indicates the current page.
Parameter pageSize: the number of pages.

For example: Query 1 page lower, set 3
insert image description here
items Example: Query 2 pages lower, set 3
insert image description here
items per page For example: Query 3 pages lower, set 3 items per page
insert image description here

Usage 4: limit with offset

The first parameter of Limit is offset, but in order to be compatible with the postgresql database, the following method can also be used in mysql. At this time, limit is only responsible for fetching the quantity, and offset is responsible for the offset. As shown below.

select * from t_user limit 6 offset 2;

insert image description here

Summarize

Word document download address: Four usages of mysql database limit

Guess you like

Origin blog.csdn.net/ma286388309/article/details/129266016