sql - `SELECT a.*, array_agg(b)` `GROUP BY` 中的所有列都需要 `a`

标签 sql postgresql

问题: 如何通过 uniq_hash (以及所有其他列)指定与 parent 相关的 child 数组,而不实际指定每一列在GROUP BY中?

数据库是PostgreSQL


我有这些表:parentschildren

parent

| id | col1 | col2 | ... | col250 | uniq_hash |
|----|------|------|-----|--------|-----------|
| 1  |      |      |     |        | <hash>    |

child

| id | bcol1 | bcol2 | ... | bcol50 | uniq_hash |
|----|-------|-------|-----|--------|-----------|
| 1  |       |       |     |        | <hash>    |
       +---------+
   +---+  Parent +---+
   |   +----+----+   |
   |        |        |
+--v--+  +--v--+  +--v--+
|Child|  |Child|  |Child|
+-----+  +-----+  +-----+


我正在尝试将 child 数组添加到 SELECT *parent FROMparents WHERE ...; 查询中。

生成的查询将类似于:

SELECTParents.*, array_agg(children) 作为子项 FROMParents LEFT JOIN 子项 ONParents.uniq_hash = Children.uniq_hash WHERE ...;


问题是 parents 的宽度约为 250 列,为此,我需要将 parents 中的每一列列为一个 GROUP通过。这……不太理想。


已经尝试过这个,它执行了 - 但它只返回两列(即:数据列上缺少标题):

选择 parent ,array_agg(children)作为 child 从 parent LEFT JOIN child 上parents.uniq_hash = Children.uniq_hash WHERE ... GROUP BY parent ;

最佳答案

事实上,你不知道。您可以只使用:

GROUP BY parents.id

如果 id 被声明为 uniqueprimary key,那么 Postgres 将接受该语法。

如果 id 没有以这种方式声明,您可以使用相关子查询:

SELECT p.*,
       (SELECT array_agg(c.children)
        FROM children c
        WHERE p.uniq_hash = c.uniq_hash
       ) as children
FROM parents p;

关于sql - `SELECT a.*, array_agg(b)` `GROUP BY` 中的所有列都需要 `a`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62311416/

相关文章:

mysql - 在一个 MySQL 表中查找一对集合

php - 如何从 MYSQL 结果集中获得 2 行的复杂总和?

Mysql 搜索高行数

sql - Django:如何有效地将 select_lated() 与 Paginator 一起使用?

postgresql - 选择十进制形式的 float

sql - Postgres 并发性和可串行化。我需要 SERIALIZABLE 隔离级别吗?

sql - 插入和更新后的 PL SQL 循环表

php - 过滤器不影响 postgreSQL 表

postgresql - Sequelize - 无法在 1 :N relationship 中保存关联

PostgreSQL 在主键上的插入因争用而失败,即使在可序列化级别也是如此