简体   繁体   中英

Postgresql: merge rows of joined query into new column array

I have this (Postgres) query:

SELECT
  p.*,
  row_to_json(c.*) as "connection"
FROM connections c
  INNER JOIN people p
  ON p.id = c.connected_to_id
WHERE c.entity_id = 1
AND c.entity_table = 'releases'
AND c.connected_to_table = 'people'

Which returns rows like this:

[
  {
    id: 1,
    name: 'Thom Yorke'
    connection: {
      id: 1,
      type: 'vocal'
    }
  },
  {
    id: 1,
    name: 'Thom Yorke'
    connection: {
      id: 2,
      type: 'instrument'
    }
  }
]

In this case there are 2 rows in the connections table associated with Thom Yorke.

I'd like to achieve this data shape:

[
  {
    id: 1,
    name: 'Thom Yorke'
    connections: [
      {
        id: 1,
        type: 'vocal'
      },
      {
        id: 2,
        type: 'instrument'
      }
    ]
  }
]

I'm struggling to find any examples (I'm not sure what terminology to search for!)

Thanks

Use json_agg() in groups by people.id:

SELECT
  p.*,
  json_agg(row_to_json(c.*)) as "connections"
FROM connections c
  INNER JOIN people p
  ON p.id = c.connected_to_id
WHERE c.entity_id = 1
AND c.entity_table = 'releases'
AND c.connected_to_table = 'people'
GROUP BY p.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM