0

I have a PostgreSQL database that looks like this:

content
id     title      content
1      Home       Welcome to the homepage

-

fields
id    contentID   value
1     1           Field Value 1
2     1           Field Value 2
3     2           Field value in other content

I'm trying to write a query which combines the data for both and ultimately comes out with:

[ { title: 'Home', content: 'Welcome to the homepage', fields: [ { id: 1, contentID: 1, value: 'Field Value 1' }, { id: 2, contentID: 1, value: 'Field Value 2' } ] } ]

Here is the query I tried, want to do it all in one query for performance:

let data = await query(`SELECT *, (SELECT array(SELECT * FROM stuff.fields WHERE stuff.fields.contentID=stuff.content.id)) as fields FROM stuff.content`);

Note that stuff is the schema name, I'm super new to PostgreSQL but I like it's data flexibility and speed compared to MySQL, and I don't think MySQL can do something like this.

Jordash
  • 2,926
  • 8
  • 38
  • 77
  • See here: https://stackoverflow.com/questions/39805736/get-join-table-as-array-of-results-with-postgresql-nodejs – vitaly-t Nov 06 '17 at 22:42

1 Answers1

1

The expected output looks like json. Use jsonb functions:

select to_jsonb(c)- 'id' || jsonb_build_object('fields', jsonb_agg(to_json(f)))
from content c
join fields f on c.id = f.content_id
group by c.id;

to get this json:

{
    "title": "Home",
    "fields": [
        {
            "id": 1,
            "value": "Field Value 1",
            "content_id": 1
        },
        {
            "id": 2,
            "value": "Field Value 2",
            "content_id": 1
        }
    ],
    "content": "Welcome to the homepage"
}
klin
  • 112,967
  • 15
  • 204
  • 232
  • What would the full statement here be: this is what I tried: `SELECT to_jsonb(stuff.content)- 'id' || jsonb_build_object('fields', jsonb_agg(to_json(stuff.fields))) FROM stuff.content JOIN stuff.fields on stuff.content.id = "stuff"."fields"."contentID" GROUP BY stuff.content.id` it says: missing FROM-clause entry for table "stuff" – Jordash Nov 07 '17 at 02:01
  • Use table aliases like in the answer. – klin Nov 07 '17 at 07:18