我在父表和子表之间有一对多关系,如下所示:
子表:
+----------+-----------+------------+--------------+
| table_id | parent_id | page_index | other_column |
+----------+-----------+------------+--------------+
| t1 | p1 | 1 | foo |
| t1 | p1 | 2 | bar |
| t2 | p2 | 1 | baz |
+----------+-----------+------------+--------------+
我想得到如下的最终结果,即按父id分组和按页索引分组:
+-----------+--------------------------------------------+
| parent_id | pages |
+-----------+--------------------------------------------+
| p1 | [{other_column: foo}, {other_column: bar}] |
| p2 | [{other_column: baz}] |
+-----------+--------------------------------------------+
我尝试了以下查询:
SELECT parent_table.parent_id, jsonb_agg(child_table.*) as pages
FROM parent_table
JOIN child_table ON child_table.parent_id = parent_table.parent_id
group by parent_table.parent_id, child_table.page_index
但是我得到了包含三行的结果,比如:
+-----------+-----------------------+
| parent_id | pages |
+-----------+-----------------------+
| p1 | [{other_column: foo}] |
| p1 | [{other_column: bar}] |
| p2 | [{other_column: baz}] |
+-----------+-----------------------+
因此,我使用子查询和按父\u id再次分组,在此基础上进行了另一次聚合,如下所示:
select sub_q.parent_id, jsonb_agg(sub_q.pages) as pages
from (
SELECT parent_table.parent_id, jsonb_agg(child_table.*) as pages
FROM parent_table
JOIN child_table ON child_table.parent_id = parent_table.parent_id
group by parent_table.parent_id, child_table.page_index
) as sub_q
按子\u q.父\u id分组
但我最终还是
+-----------+------------------------------------------------+
| parent_id | pages |
+-----------+------------------------------------------------+
| p1 | [[{other_column: foo}], [{other_column: bar}]] |
| p2 | [{other_column: baz}] |
+-----------+------------------------------------------------+
如何使用最佳查询使每一行都具有一维数组,从而获得上述所需的结果?
如果答案有分贝小提琴就好了!
1条答案
按热度按时间gkl3eglg1#
你好像把事情搞得太复杂了。如示例数据所示,您可以通过简单的聚合直接从子表中获取所需的信息:
db小提琴演示: