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

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

    As a slight variation on @wildplasser's suggestion, which still works across implementations, you can use max rather than not exists. This reads better if you like short joins better than long where clauses

    select * 
      from author au
      join (
        select max(id) as max_id, author_id
          from book bk
         group by author_id) as lb 
        on lb.author_id = au.id
      join bk 
        on bk.id = lb.max_id;
    

    or, to give a name to the subquery, which clarifies things, go with WITH

    with last_book as 
       (select max(id) as max_id, author_id
          from book bk
         group by author_id)
    
    select * 
      from author au
      join last_book lb
        on au.id = lb.author_id
      join bk 
        on bk.id = lb.max_id;
    

提交回复
热议问题