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

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

    You could add a rule into the join for specifying only one row. I had work for me.

    Like this:

    SELECT 
        book.id, 
        author.id, 
        author.name, 
        book.title as last_book
    FROM author auth1
    JOIN book book ON (book.author_id = auth1.id AND book.id = (select max(b.id) from book b where b.author_id = auth1))
    GROUP BY auth1.id
    ORDER BY book.id ASC
    

    This way you get the data from the book with the higher ID. You could add "date" and make the same with the max(date).

提交回复
热议问题