问题:
如何通过 uniq_hash
(以及所有其他列)指定与 parent
相关的 child
数组,而不实际指定每一列在GROUP BY
中?
数据库是PostgreSQL。
我有这些表:parents
和 children
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
被声明为 unique
或 primary 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/