【问题标题】:Aggregate query result汇总查询结果
【发布时间】:2021-12-08 16:45:43
【问题描述】:

我有两个表,第二个表包含一个引用第一个表主键的外键。

第一个表“Houses”(id,title,city,country),第二个表“Images”(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 数据库。

【问题讨论】:

  • 结果中的id 很奇怪。

标签: database postgresql knex.js


【解决方案1】:

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;

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2015-06-27
    • 2011-09-30
    • 1970-01-01
    相关资源
    最近更新 更多