Paging with LIMIT

In MySQL, use to LIMITimplement paging, the syntax is as follows:

  • MySQL5.7, LIMIT 初始位置,记录数or LIMIT 位置偏移量,记录数.
  • In MySQL8.0, LIMIT 记录数 OFFSET 位置偏移量.

LIMIT 0,记录数Alternatively , LIMIT 记录数 OFFSET 0it can be abbreviated as LIMIT 记录数.

LIMIT initial position, number of records

Assuming that when paging, pageSizerecords , and pageNothe page is displayed at this time, then LIMIT (pageNo-1)*pageSize,pageSize.

1. Query all the data in the table employees.

# 查询表employees中的所有数据
SELECT employee_id,last_name,salary
FROM employees;

insert image description here

2. Each page displays 10 records, and the first page is displayed at this time.

# 每页显示10条记录,此时显示第1页
SELECT employee_id,last_name,salary
FROM employees
LIMIT 0,10;

insert image description here
3. Each page displays 10 records, and the second page is displayed at this time.

# 每页显示10条记录,此时显示第2页
SELECT employee_id,last_name,salary
FROM employees
LIMIT 10,10;

insert image description here
4. Each page displays 10 records, and the third page is currently displayed.

# 每页显示10条记录,当前显示第3页
SELECT employee_id,last_name
FROM employees
LIMIT 20,10;

insert image description here
5. There are 107 pieces of data in the table, and only want to display the 32nd and 33rd pieces of data.

# 表里有107条数据,只想显示第32、33条数据
SELECT employee_id,last_name,salary
FROM employees
LIMIT 31,2;

insert image description here

LIMIT number of records OFFSET offset

1. There are 107 pieces of data in the table, and only want to display the 32nd and 33rd pieces of data.

# 表里有107条数据,只想显示第32、33条数据
SELECT employee_id,last_name,salary
FROM employees
LIMIT 2 OFFSET 31;

insert image description here
2. Query the employee information with the highest salary.

# 查询工资最高的员工信息
SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary DESC
LIMIT 1;

SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary DESC
LIMIT 0,1;

SELECT employee_id,last_name,salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 0;

insert image description here

LIMIT 0, number of records, LIMIT number of records OFFSET 0, LIMIT number of records

LIMIT 0,记录数, LIMIT 记录数 OFFSET 0, can be abbreviated as LIMIT 记录数.

1. Query employee information whose salary is greater than 6000, then sort the data in descending order of salary, and get the first 10 records.

# LIMIT 0,10
SELECT employee_id,last_name,salary
FROM employees
WHERE salary > 6000
ORDER BY salary DESC
LIMIT 0,10;

# LIMIT 10 OFFSET 0
SELECT employee_id,last_name,salary
FROM employees
WHERE salary > 6000
ORDER BY salary DESC
LIMIT 10 OFFSET 0;

# LIMIT 10
SELECT employee_id,last_name,salary
FROM employees
WHERE salary > 6000
ORDER BY salary DESC
LIMIT 10;

insert image description here

Guess you like

Origin blog.csdn.net/qzw752890913/article/details/126039481