PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

PostgreSQL , Seleziona da 2 tabelle, ma solo l'ultimo elemento dalla tabella 2

Usa PostgreSQL estensione DISTINCT ON :

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

Questo prenderà la prima riga da ogni document.id cluster in ORDER BY ordine.

Script di prova da verificare:

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