我在PostgreSQL COUNTRIES和CITIES中有两个表。我将node-postgres用于nodejs。
COUNTRIES
id name
1 USA
2 GERMANY
3 CHINA
城市
id name country_id
1 New York 1
2 Chicago 1
3 Hong Kong 3
4 Boston 1
5 Beijing 3
6 Berlin 2
[如果可能。我可以得到类似的数据吗?
[{
id: 1,
country: 'USA',
cities: [{
id: 1,
city: 'New York',
},{
id: 2,
city: 'Chicago',
},{
id: 4,
city: 'Boston',
}]
}, {
id: 2,
country: 'GERMANY',
cities: [{
id: 6,
city: 'Berlin',
}],
...
}]
在Postgres中,您可以汇总为:
select c.id, c.name, array_agg( (ci.id, ci.name) ) as cities
from countries c join
cities ci
on ci.country_id = c.id
group by c.id;
这将使用Postgres类型返回结果。