跳转至内容

SQL 方言参考/选择查询/限制返回的行数

来自维基教科书,开放书籍,开放世界

限制返回的行数

[编辑 | 编辑源代码]

注意:end_row = start_row + num_rows - 1

标准 SELECT columns FROM table FETCH FIRST num_rows ROWS ONLY

SELECT columns FROM table OFFSET start_row ROWS FETCH FIRST num_rows ROWS ONLY

DB2 SELECT columns FROM table FETCH FIRST num_rows ROWS ONLY
Firebird 版本 > 2.0
SELECT columns FROM table ROWS start_row TO end_row

所有版本

SELECT FIRST num_rows SKIP start_row columns FROM table
Ingres
  • SELECT FIRST num_rows columns FROM table
  • SELECT columns FROM table OFFSET start_row FETCH {FIRST|NEXT} num_rows ROWS ONLY
Linter
SELECT columns FROM table FETCH FIRST num_rows
SELECT columns FROM table LIMIT start_row, num_rows
(rows are numbered from 0)
MonetDB SELECT columns FROM table LIMIT num_rows OFFSET start_row
MSSQL
  • SELECT columns FROM table OFFSET start_row ROWS FETCH { FIRST | NEXT } num_rows ROW[S] ONLY
  • 简单版本(当 start_row = 0 时)
SELECT TOP num_rows columns FROM table
MySQL 版本 > 4.0.14
SELECT columns FROM table LIMIT num_rows OFFSET start_row

所有版本

SELECT columns FROM table LIMIT start_row, num_rows
Oracle 简单查询
-- Notice: Will not work, if start_row > 1, since the first row will return false, and the cursor will terminate.
SELECT columns FROM table WHERE rownum >= start_row AND rownum <= end_row

这在不指定 start_row 的情况下也能正常工作

SELECT columns FROM table WHERE rownum <= end_row

这也能工作,但结果集中会附加 num 列

SELECT * FROM (
  SELECT temp.*, rownum num FROM table ORDER BY columns
  ) WHERE num >= start_row and num <= end_row

自 12.1 起,类似于标准

SELECT columns FROM table FETCH FIRST num_rows ROWS ONLY
SELECT columns FROM table OFFSET start_row ROWS FETCH FIRST num_rows ROWS ONLY

完整语法:(可以有 OFFSET、FETCH 或两个子句)

SELECT column [, column2 …] FROM table [ORDER BY column2] 
[OFFSET start_row ROWS] 
[FETCH [FIRST|NEXT] [num_rows|percent PERCENT] ROWS [ONLY|WITH TIES]]
PostgreSQL SELECT columns FROM table LIMIT num_rows OFFSET start_row

或:SQL 标准语法。

SQLite SELECT columns FROM table LIMIT num_rows OFFSET start_row
Virtuoso
SELECT TOP num_rows columns FROM table
SELECT TOP skip_rows,num_rows columns FROM table


标准 -
DB2 ?
Firebird ?
Ingres ?
Linter ?
MonetDB ?
MSSQL NOT IN()
MySQL NOT IN()
Oracle MINUS
PostgreSQL ?
SQLite ?
Virtuoso ?
华夏公益教科书