本章我们学习 LIMIT
、OFFSET
和 FETCH
子句。和 LIMIT
一样,FETCH
也是为了限定返回的行数,但你不知道的是,FETCH
才是 SQL 标准,而 LIMIT
不是。
我们先来看一下大部分数据库都支持的、日常开发最熟悉的 LIMIT
,虽然 FETCH
才是 SQL 标准,但是 LIMIT
无疑是在日常中用的最多的。
LIMIT
和 OFFSET
子句
LIMIT n OFFSET m
典型应用就是翻页- MySQL 8 开始支持
LIMIT n OFFSET m
语法
本章我们以示例数据库中的 film
表作演示。
Table "public.film"
Column | Type | Collation | Nullable | Default
------------------+-----------------------------+-----------+----------+---------------------------------------
film_id | integer | | not null | nextval('film_film_id_seq'::regclass)
title | character varying(255) | | not null |
description | text | | |
release_year | year | | |
language_id | smallint | | not null |
rental_duration | smallint | | not null | 3
rental_rate | numeric(4,2) | | not null | 4.99
length | smallint | | |
replacement_cost | numeric(5,2) | | not null | 19.99
rating | mpaa_rating | | | 'G'::mpaa_rating
last_update | timestamp without time zone | | not null | now()
special_features | text[] | | |
fulltext | tsvector | | not null |
示例如下:
-- 返回按 film_id 升序排序的前5部电影
SELECT film_id, title, release_year FROM film ORDER BY film_id LIMIT 5;
-- 返回跳过3部电影之后,按 film_id 升序排序的前4部电影
SELECT film_id, title, release_year FROM film ORDER BY film_id LIMIT 4 OFFSET 3;
-- 返回租赁费用最高的10部电影
SELECT film_id, title, rental_rate FROM film ORDER BY rental_rate DESC LIMIT 10;