Skip to content
Advertisement

Get latest child row with parent table row

Two tables posts and comments. posts has many comments (comments has post_id foreign key to posts id primary key)

I need all posts, its content, and latest comment (based on max(created_at), and its text.

I can get upto created_at using this

But I want the text of the comment as well.

Advertisement

Answer

You can use the Postgres extension distinct on:

This sorts the data by the order by clause, returning the first row based on the keys in the distinct on.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement