按id选择行,然后选择它';s按某个值排序的最近行。PostgreSQL

按id选择行,然后选择它';s按某个值排序的最近行。PostgreSQL,postgresql,Postgresql,我有这样的表格: id | title | sort_number | book_id 1 | 'Chap 1' | 3 | 1 5 | 'Chap 2' | 6 | 1 8 | 'About ' | 1 | 1 9 | 'Chap 3' | 9 | 1 10 | 'Attack' | 1 | 2 Id是唯一的,同一本书的排序号是唯一的(书Id) 1) 如果我只有当前章节id,如何

我有这样的表格:

id | title    | sort_number | book_id
1  | 'Chap 1' | 3           | 1
5  | 'Chap 2' | 6           | 1
8  | 'About ' | 1           | 1
9  | 'Chap 3' | 9           | 1
10 | 'Attack' | 1           | 2
Id是唯一的,同一本书的排序号是唯一的(书Id)

1) 如果我只有当前章节id,如何加载按排序号排序的3个章节(当前、下一个和上一个)的所有数据(3行)

2) 如何加载当前章节数据(1行)以及仅加载下一个、上一个(如果存在)的id?

可以使用

使用返回的示例数据:

id | title  | sort_number | book_id | prev_chapter | next_chapter
---+--------+-------------+---------+--------------+-------------
 8 | About  |           1 |       1 |              |            1
 1 | Chap 1 |           3 |       1 |            8 |            5
 5 | Chap 2 |           6 |       1 |            1 |            9
 9 | Chap 3 |           9 |       1 |            5 |             
10 | Attack |           1 |       2 |              |             
以上查询现在可用于回答您的两个问题:

(一)

(二)

id | title  | sort_number | book_id | prev_chapter | next_chapter
---+--------+-------------+---------+--------------+-------------
 8 | About  |           1 |       1 |              |            1
 1 | Chap 1 |           3 |       1 |            8 |            5
 5 | Chap 2 |           6 |       1 |            1 |            9
 9 | Chap 3 |           9 |       1 |            5 |             
10 | Attack |           1 |       2 |              |             
select id, title, sort_number, book_id
from (
  select id, title, sort_number, book_id, 
         --first_value(id) over w as first_chapter,
         lag(id) over w as prev_chapter_id,
         lead(id) over w as next_chapter_id
  from chapters
  window w as (partition by book_id order by sort_number)
) t
where 1 in (id, prev_chapter_id, next_chapter_id)
select *
from (
  select id, title, sort_number, book_id, 
         lag(id) over w as prev_chapter_id,
         lead(id) over w as next_chapter_id
  from chapters
  window w as (partition by book_id order by sort_number)
) t
where id = 1