PostgreSQL , Select from 2 tables, but only the latest element from table 2

后端 未结 5 2066
星月不相逢
星月不相逢 2021-02-07 07:07

Hey, I have 2 tables in PostgreSql:

1 - documents: id, title
2 - updates: id, document_id, date

and some data:

documents:

5条回答
  •  -上瘾入骨i
    2021-02-07 07:26

    select *
    from documents
    left join updates
      on updates.document_id=documents.id
      and updates.date=(select max(date) from updates where document_id=documents.id)
    where documents.id=?;
    

    It has the some advantages over previous answers:

    • you can write document_id only in one place which is convenient;
    • you can omit where and you'll get a table of all documents and their latest updates;
    • you can use more broad selection criteria, for example where documents.id in (1,2,3).

    You can also avoid a subselect using group by, but you'll have to list all fields of documents in group by clause:

    select documents.*, max(date) as max_date
      from documents
      left join updates on documents.id=document_id
      where documents.id=1
      group by documents.id, title;
    

提交回复
热议问题