聚合查询结果
Aggregate query result
我有两个 table,第二个 table 包含引用第一个 table 主键的外键。
第一个 table“房屋”(id,title,city,country),第二个 table“图片”(id,name,house_id)
我正在执行以下查询:
SELECT * FROM houses INNER JOIN images ON houses.id = images.house_id;
结果是一个重复数据数组,除了一个字段名:
[
{
id:1,
title: "house1",
city:"c1",
country:"country2",
name:"image1",
house_id: 2
},
{
id:2,
title: "house1",
city:"c1",
country:"country2",
name:"image2",
house_id: 2
},
{
id:3,
title: "house1",
city:"c1",
country:"country2",
name:"image3"
house_id: 2,
},
]
如何调整查询以获得如下结果:
[
{
id:2,
title: "house1",
city:"c1",
country:"country2",
imagesNames:["image1","image2","image3"]
house_id: 2,
}
]
用knex可以吗?我正在使用 PostgreSQL 数据库。
GROUP BY
所有对等点共享的所有列,以及聚合名称。喜欢:
SELECT h.id, h.title, h.city, h.country
, array_agg(name) AS images_names
, i.house_id -- redundant?
FROM houses h
JOIN images i ON h.id = i.house_id;
GROUP BY h.id, h.title, h.city, h.country, i.house_id;
我有两个 table,第二个 table 包含引用第一个 table 主键的外键。
第一个 table“房屋”(id,title,city,country),第二个 table“图片”(id,name,house_id)
我正在执行以下查询:
SELECT * FROM houses INNER JOIN images ON houses.id = images.house_id;
结果是一个重复数据数组,除了一个字段名:
[
{
id:1,
title: "house1",
city:"c1",
country:"country2",
name:"image1",
house_id: 2
},
{
id:2,
title: "house1",
city:"c1",
country:"country2",
name:"image2",
house_id: 2
},
{
id:3,
title: "house1",
city:"c1",
country:"country2",
name:"image3"
house_id: 2,
},
]
如何调整查询以获得如下结果:
[
{
id:2,
title: "house1",
city:"c1",
country:"country2",
imagesNames:["image1","image2","image3"]
house_id: 2,
}
]
用knex可以吗?我正在使用 PostgreSQL 数据库。
GROUP BY
所有对等点共享的所有列,以及聚合名称。喜欢:
SELECT h.id, h.title, h.city, h.country
, array_agg(name) AS images_names
, i.house_id -- redundant?
FROM houses h
JOIN images i ON h.id = i.house_id;
GROUP BY h.id, h.title, h.city, h.country, i.house_id;