【问题标题】:Select row by id and it's nearest rows sorted by some value. PostgreSQL按 id 选择行,它是按某个值排序的最近行。 PostgreSQL
【发布时间】:2019-08-23 20:35:03
【问题描述】:

我有这样的章节表:

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是唯一的,sort_number对于同一本书是唯一的(book_id)

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

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

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    这可以使用window functions来完成

    select id, title, sort_number, book_id, 
           lag(id) over w as prev_chapter,
           lead(id) over w as next_chapter
    from chapters
    window w as (partition by book_id order by sort_number);
    

    使用返回的示例数据:

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

    以上查询现在可用于回答您的两个问题:

    1)

    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)
    

    2)

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多