How to join only one row in joined table with postgres?

后端 未结 7 499
清歌不尽
清歌不尽 2021-01-31 01:31

I have the following schema:

CREATE TABLE author (
    id   integer
  , name varchar(255)
);
CREATE TABLE book (
    id        integer
  , author_id integer
  ,          


        
7条回答
  •  失恋的感觉
    2021-01-31 02:28

    Here is one way:

    SELECT book_id, author_id, author_name, last_book
    FROM (
        SELECT b.id as book_id
             , a.id as author_id
             , a.name as author_name
             , b.title as last_book
             , row_number() over (partition by a.id
                                  order by b.id desc) as rn
        FROM author a
        JOIN book b 
            ON b.author_id = a.id
    ) last_books
    WHERE rn = 1;
    

提交回复
热议问题