PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

Comment joindre une seule ligne dans une table jointe avec 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

Vérifiez distinct on

Avec distinct on il faut inclure les colonnes "distinct" dans le order by . Si ce n'est pas la commande que vous souhaitez, vous devez envelopper la requête et réorganiser

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

Une autre solution consiste à utiliser une fonction de fenêtre comme dans la réponse de Lennart. Et un autre très générique est celui-ci

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