我有两张桌子。一个是事件,另一个是人。它们看起来像这样:
{
"event_id": 1,
"start": Fri, 05 Aug 2016 21:18:38 GMT,
"end": Fri, 05 Aug 2016 21:18:38 GMT,
"guests": [
{"name": "John", event_id: 1}, //record from people table
{"name": "Sarah", event_id: 1}
]
}
我想查询单个事件以获取事件信息,但我还想获得一个将要参加活动的访客列表(与人相关)。
我最终寻找的输出看起来像这样(转换为json):
SELECT
*
FROM events, people
WHERE events.event_id = people.event_id
如何在Postgresql中优雅地执行连接,以检索我拥有的所有相关人员记录?
到目前为止,我有以下查询:
find_paths
答案 0 :(得分:1)
不确定如果我正确地嘲笑你的桌子。这样做了吗?
with events as (select * from events)
select jsonb_set(
to_jsonb(events.*)
, '{guests}'
,to_jsonb(array_agg(to_json(people))
)
)
from people
join events on people.event_id = events.event_id
group by events.*
;