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

后端 未结 5 2067
星月不相逢
星月不相逢 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:47

    Use PostgreSQL extension DISTINCT ON:

    SELECT  DISTINCT ON (documents.id) *
    FROM    document
    JOIN    updates
    ON      updates.document_id = document_id
    ORDER BY
            documents.id, updates.date DESC
    

    This will take the first row from each document.id cluster in ORDER BY order.

    Test script to check:

    SELECT  DISTINCT ON (documents.id) *
    FROM    (
            VALUES
            (1, 'Test Title'),
            (2, 'Test Title 2')
            ) documents (id, title)
    JOIN    (
            VALUES
            (1, 1, '2006-01-01'::DATE),
            (2, 1, '2007-01-01'::DATE),
            (3, 1, '2008-01-01'::DATE),
            (4, 2, '2009-01-01'::DATE),
            (5, 2, '2010-01-01'::DATE)
            ) updates (id, document_id, date)
    ON      updates.document_id = documents.id
    ORDER BY
            documents.id, updates.date DESC
    

提交回复
热议问题