我有这个(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'
}
]
}
]
我很难找到任何例子(我不确定要搜索的术语!)
由于
答案 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;