sql - `SELECT a.*, array_agg(b)` 需要 `a` 中所有列的 `GROUP BY`
问题描述
问题:
如何指定我想要一个与by (以及所有其他列)child
相关的数组,而无需实际指定 中的每一列?parent
uniq_hash
GROUP BY
数据库是PostgreSQL。
我有这些表:parents
和children
parents
| id | col1 | col2 | ... | col250 | uniq_hash |
|----|------|------|-----|--------|-----------|
| 1 | | | | | <hash> |
children
| id | bcol1 | bcol2 | ... | bcol50 | uniq_hash |
|----|-------|-------|-----|--------|-----------|
| 1 | | | | | <hash> |
+---------+
+---+ Parent +---+
| +----+----+ |
| | |
+--v--+ +--v--+ +--v--+
|Child| |Child| |Child|
+-----+ +-----+ +-----+
我正在尝试将数组添加child
到SELECT * parent FROM parents WHERE ...;
查询中。
生成的查询将类似于:
SELECT parents.*, array_agg(children) as children FROM parents LEFT JOIN children ON parents.uniq_hash = children.uniq_hash WHERE ...;
问题是parents
大约 250 列宽,要做到这一点,我似乎需要将每一列parents
列为GROUP BY
. 这是……次优的。
我已经尝试过了,它执行了——但它只返回两列(即:它缺少parent
数据列上的标题):
SELECT parents, array_agg(children) as children FROM parents LEFT JOIN children ON parents.uniq_hash = children.uniq_hash WHERE ... GROUP BY parents;
解决方案
事实上,你没有。你可以使用:
GROUP BY parents.id
如果id
声明为unique
or 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;
推荐阅读
- vba - 在 MS word 中转换大小写
- mongodb - 带有 MongoDB-4.0 的 Apache Kafka 的官方 MongoDB 源连接器
- r - 刚刚下载了 R 版本 4.0.0 并且无法使用?
- java - 我该如何处理这个错误“在任何可用的数据中心中找不到合适的主机。”?
- vue.js - Route.push 在第二次尝试中无法正常工作
- python - 如何调试由 crontab 执行的 python 脚本?
- java - 粘贴输入时,Java Stream 仅复制第一行
- reactjs - JWT 身份验证令牌未定义
- javascript - VueJS没有在for循环内渲染数据集
- php - 无法安装php包?