LIMIT、OFFSET 和 FETCH 子句

我们先来看一下大部分数据库都支持的、日常开发最熟悉的 LIMIT,虽然 FETCH 才是 SQL 标准,但是 LIMIT 无疑是在日常中用的最多的。

  • 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 | 

示例如下:

-- 返回按标题升序排序的第一部电影
SELECT film_id, title FROM film ORDER BY title FETCH FRIST ROW ONLY;

-- 等同于上例 
SELECT film_id, title FROM film ORDER BY title FETCH FRIST 1 ROW ONLY;

-- 返回按标题升序排序的前5部电影
SELECT film_id, title FROM film ORDER BY title FETCH FRIST 5 ROW ONLY;

-- 返回跳过5部电影之后,按标题升序排序的前5部电影
SELECT film_id, title FROM film ORDER BY title OFFSET 5 ROWS FETCH FRIST 5 ROW ONLY;
要查看完整内容,请先登录