SELECT coalesce(jsonb_agg(result), '[]') AS result FROM (SELECT to_jsonb ("books".*)
||
jsonb_build_object(
authors::text,
"lateral_authors".result,
tags::text,
"lateral_tags".result)
AS result FROM "books" "sq_books" LEFT JOIN LATERAL (SELECT to_jsonb ("authors".*) AS result FROM "authors" WHERE id
= books.authorId
LIMIT 1) lateral_authors ON true LEFT JOIN LATERAL (SELECT coalesce(jsonb_agg(result), '[]') AS result FROM "tags" WHERE bookId = books.id) lateral_tags ON true) sq_books