0

Hello guys i'm facing a problem when using json_agg

i have two tables : docs and subs that look like this

Docs(
id primary key,
title,
name,
code
)
Subs(
id primary key,
title,
name,
code,
idoc fk
)

and i use this query to retrieve them

SELECT *,s.subdocs FROM docs d INNER JOIN(
    SELECT idoc,json_agg(
        json_build_object(
        'id',id,'title',title,'name',name,'code',code,
    )) AS subdocs FROM subs GROUP BY subs.idoc
    ) AS s ON s.idoc = d.idoc
 WHERE d.id = 4

It seem to work when there is a sub doc associated with the doc but when there is not the query doesn't return anything so how can i check if the result of the json agg is empty and to return at least the fields of the docs table?

1
  • please provide sample data and desired output Commented Apr 17, 2021 at 18:58

1 Answer 1

1

seems like you need to use left join :

SELECT *,s.subdocs FROM docs d 
LEFT JOIN (
    SELECT idoc,json_agg(json_build_object('id',id,'title',title,'name',name,'code',code)) AS subdocs 
    FROM subs GROUP BY subs.idoc
    ) AS s ON s.idoc = d.idoc
 WHERE d.id = 4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.