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

后端 未结 7 488
清歌不尽
清歌不尽 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:06

    This may look archaic and overly simple, but it does not depend on window functions, CTE's and aggregating subqueries. In most cases it is also the fastest.

    SELECT bk.id, au.id, au.name, bk.title as last_book
    FROM author au
    JOIN book bk ON bk.author_id = au.id
    WHERE NOT EXISTS (
        SELECT *
        FROM book nx
        WHERE nx.author_id = bk.author_id
        AND nx.book_id > bk.book_id
        )
    ORDER BY book.id ASC
        ;
    

提交回复
热议问题