Reputation: 1667
Assume you have database with author
and book
tables.
I want to get 10 most recent books for each author.
Normally it is N+1 SQL queries.
SELECT * FROM author
-> N rows.SELECT * FROM book WHERE authorId=$1 ORDER BY releaseDate LIMIT=10
.I want to have only 1 instead of N queries, to get 10 most recent books for list of authors. ( maybe it does not make sense in case of performance / but I do not know )
SELECT * FROM book WHERE authorId = ANY($1) ORDER BY releaseDate DESC LIMIT 10
Is there a way to make SQL query to return most recent books for list of authors? Thanks.
Upvotes: 1
Views: 1078
Reputation: 13049
An alternative to window functions using lateral join:
select a.authorid, b.*
from author a
cross join lateral
(
select * from books
where books.authorid = a.authorid
order by releasedate desc
limit 10
) b;
Upvotes: 2
Reputation: 37473
You can try using row_number()
select * from
(
select *,row_number() over(partition by a.authorid order by releasedate desc) as rn
from author a join books b on a.authorid=b.authorid
)f where rn<=10
Upvotes: 2