Skip to content

Instantly share code, notes, and snippets.

@41y08h
Created May 25, 2021 01:29
Show Gist options
  • Save 41y08h/0ad96bd4f8901a48286c0038e9655703 to your computer and use it in GitHub Desktop.
Save 41y08h/0ad96bd4f8901a48286c0038e9655703 to your computer and use it in GitHub Desktop.
select posts.id,
title,
(case when count(c) = 0 then cast('[]' as json) else array_to_json(array_agg(c.obj)) end) AS comments
from posts
left join (select post_id, json_build_object('id', id, 'message', message) as obj from comments) c on posts.id = c.post_id
group by posts.id
order by title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment