sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Cómo unir solo una fila en la tabla unida con postgres?

select distinct on (author.id)
    book.id, author.id, author.name, book.title as last_book
from
    author
    inner join
    book on book.author_id = author.id
order by author.id, book.id desc

Compruebe distinct on

Con distinto activado es necesario incluir las columnas "distintas" en el order by . Si ese no es el orden que desea, debe ajustar la consulta y reordenar

select 
    *
from (
    select distinct on (author.id)
        book.id, author.id, author.name, book.title as last_book
    from
        author
        inner join
        book on book.author_id = author.id
    order by author.id, book.id desc
) authors_with_first_book
order by authors_with_first_book.name

Otra solución es usar una función de ventana como en la respuesta de Lennart. Y otra muy genérica es esta

select 
    book.id, author.id, author.name, book.title as last_book
from
    book
    inner join
    (
        select author.id as author_id, max(book.id) as book_id
        from
            author
            inner join
            book on author.id = book.author_id
        group by author.id
    ) s
    on s.book_id = book.id
    inner join
    author on book.author_id = author.id