Postgresql:将连接查询的行合并到新的列数组中

时间:2018-02-05 10:21:32

标签: sql json postgresql

我有这个(Postgres)查询:

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'

返回如下行:

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

在这种情况下,连接表中有2行与Thom Yorke相关联。

我想实现这种数据形式:

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

我很难找到任何例子(我不确定要搜索的术语!)

由于

1 个答案:

答案 0 :(得分:1)

people.id:

分组中使用json_agg()
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;