You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中父子表关联统计的高效查询方案咨询

问题

我有两个表,为灵活一对多关系(即父表记录可能无对应子表):

表结构

Parent_table

id   dim1   price
1    "abc"  1.00
2    "abc"  2.00
3    "def"  1.00

child_table

id       parent_id
1          1
2          1

基础查询

父表的基础统计查询很简单:

select dim1, count(*), sum(price) from parent_table group by dim1

需求与问题

现在需要在上述查询中新增统计项child_count(每个dim1分组下对应的子表记录总数)。

直接左关联子表的写法性能尚可,但会导致父表字段重复计数(因为一对多关联后父表记录会被复制):

select p.dim1, count(*), sum(p.price), count(distinct c.id) as child_count
from parent_table p
  left outer join child_table c on c.parent_id = p.id
group by dim1

我尝试了下面的查询,理论上能实现需求,但由于表数据量极大,无法验证:

-- 注:原查询存在语法错误,已修正:sum(*)改为count(*),子表查询补充group by,添加coalesce处理空值
select p.dim1, count(*), sum(p.price), sum(coalesce(child_count, 0)) as child_count
from parent_table p
  left outer join (select c.parent_id, count(c.id) child_count from child_table c group by c.parent_id) child on p.id = child.parent_id
group by dim1

请问PostgreSQL是否有无需嵌套子查询即可实现该需求的高效方法?


编辑:我修正了原问题中的错误,调整内容如下:

add 2 more rows to parent table
delete quantity column  
change count(quantity) --> count(*)

编辑2:我想到了以下相关子查询的写法,在PostgreSQL中测试下来比单次关联性能更好:

-- 注:原查询缺少右括号,已修正
select p.dim1, count(*), sum(p.price), 
  sum(coalesce((select count(distinct id) from child_table where parent_id = p.id), 0)) as child_count
from parent_table p
group by dim1

请问这个方案的可行性如何?


内容的提问来源于stack exchange,提问作者user3758745

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:52:51