1

I am trying to have my query return JSON to be used in an API. I am using the PostGIS extension to deal with location information. The PostGIS extension is working well and not an issue with this problem. I only mention this because there are functions in the query related to the PostGIS extension. I have these objects of the JSON document:

  • main Company document (OK)
  • Events related to companies (OK)
  • Dates related to the Events (* this is where we have a problem)
  • Addresses related to Companies (OK)
  • Cities related to Companies (OK)

Here is my SQL statement:

SELECT c.id, c.name, c.website, c.longdescription, c.description, c.email, 
jsonb_agg((SELECT ev FROM (SELECT ev.title, ev.description, ev.longdescription, jsonb_agg((SELECT ed FROM(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed)) AS dates, ev.id WHERE ev.id notnull)ev)) AS events, 
jsonb_agg((SELECT ca FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) AS latitude, ST_X(ca.geopoint::geometry) AS longitude WHERE ca.id notnull)ca)) AS addresses
FROM companies c
LEFT JOIN events ev ON ev.company_id = c.id
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
LEFT JOIN eventdates ed ON ed.event_id = ev.id
GROUP BY c.id

Any ideas how I could reform as not to have the nested functions and still arrive at the correct result?

1 Answer 1

1

The problematic line is

jsonb_agg((SELECT ev FROM (SELECT ev.title, ev.description, ev.longdescription, jsonb_agg((SELECT ed FROM(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed)) AS dates, ev.id WHERE ev.id notnull)ev)) AS events, 

I think it will work, if you move the jsonb_agg into the second subquery. So change

jsonb_agg((SELECT ed FROM(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed)) AS dates

into

(SELECT jsonb_agg(ed) FROM(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed) AS dates

I'm not sure this will work, but if you provide CREATE statements to the ed and ev tables, I can refine it.

Sign up to request clarification or add additional context in comments.

1 Comment

So I didn't realize that I had duplicated records due to the joins. Any suggestions? Thanks again.

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.