温馨提示×

三种SQL分页语句

sql
小云
159
2023-09-22 07:52:43
栏目: 云计算

在SQL中,有多种方法可以进行分页查询。以下是三种常用的SQL分页语句示例:

  1. 使用LIMIT和OFFSET关键字:
SELECT column1, column2, ...
FROM table
LIMIT <num_rows> OFFSET <offset>

其中,<num_rows>指定每页返回的行数,<offset>指定从结果集的第几行开始返回数据。

例如,要返回第1页,每页10行数据的查询结果:

SELECT column1, column2, ...
FROM table
LIMIT 10 OFFSET 0

要返回第2页查询结果:

SELECT column1, column2, ...
FROM table
LIMIT 10 OFFSET 10
  1. 使用ROW_NUMBER()函数:
SELECT column1, column2, ...
FROM (
SELECT column1, column2, ..., ROW_NUMBER() OVER (ORDER BY column_name) AS row_num
FROM table
) AS subquery
WHERE row_num BETWEEN <start_row> AND <end_row>

其中,<start_row><end_row>分别指定每页的起始行和结束行。

例如,要返回第1页,每页10行数据的查询结果:

SELECT column1, column2, ...
FROM (
SELECT column1, column2, ..., ROW_NUMBER() OVER (ORDER BY column_name) AS row_num
FROM table
) AS subquery
WHERE row_num BETWEEN 1 AND 10

要返回第2页查询结果:

SELECT column1, column2, ...
FROM (
SELECT column1, column2, ..., ROW_NUMBER() OVER (ORDER BY column_name) AS row_num
FROM table
) AS subquery
WHERE row_num BETWEEN 11 AND 20
  1. 使用OFFSET FETCH NEXT关键字(仅适用于SQL Server和Oracle数据库):
SELECT column1, column2, ...
FROM table
ORDER BY column_name
OFFSET <offset> ROWS FETCH NEXT <num_rows> ROWS ONLY

其中,<offset>指定从结果集的第几行开始返回数据,<num_rows>指定每页返回的行数。

例如,要返回第1页,每页10行数据的查询结果:

SELECT column1, column2, ...
FROM table
ORDER BY column_name
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

要返回第2页查询结果:

SELECT column1, column2, ...
FROM table
ORDER BY column_name
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY

请注意,以上示例中的tablecolumn_name需要替换为实际的表名和列名。

0