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

如何编写SQLAlchemy联表查询:每个父行仅返回一行且取最小ID子行

实现SQLAlchemy关联父级与最小ID子级的查询

针对你的需求——每个父级返回一行,无子级时仍显示父行,有多子级时仅关联ID最小的子级,这里提供两种可行的实现方案,适配你使用的PostgreSQL环境:

先修正模型的小问题

原模型中__table_args__的定义缺少逗号,会导致SQLAlchemy解析异常,需调整为:

# Parent类修正后
__table_args__ = (PrimaryKeyConstraint("id"),)

# Child类修正后
__table_args__ = (PrimaryKeyConstraint("id"),)

方案一:子查询筛选最小子级ID

通过子查询先按父ID分组,获取每个父级对应的最小子级ID,再关联回子表得到完整子级记录,最后与父表左连接:

from sqlalchemy import select, func
from sqlalchemy.orm import aliased

# 子查询:获取每个parent_id对应的最小child id
min_child_subq = (
    select(
        Child.parent_id,
        func.min(Child.id).label("min_child_id")
    )
    .group_by(Child.parent_id)
    .subquery()
)

# 关联子查询与Child表,得到最小ID的子级记录
child_alias = aliased(Child)
min_child = (
    select(child_alias)
    .join(
        min_child_subq,
        (child_alias.parent_id == min_child_subq.c.parent_id) & 
        (child_alias.id == min_child_subq.c.min_child_id)
    )
    .subquery()
)

# 左连接父表与筛选后的子级,确保无子级的父行也被保留
query = (
    select(Parent, min_child)
    .outerjoin(
        min_child,
        Parent.id == min_child.c.parent_id
    )
)

# 执行查询(假设已有session对象)
results = session.execute(query).all()

方案二:窗口函数(PostgreSQL推荐)

利用PostgreSQL的窗口函数ROW_NUMBER(),按父ID分区、子ID升序给子级记录打行号,筛选行号为1的记录即为每个父级最小ID的子级,性能优于子查询方案(数据量大时更明显):

from sqlalchemy import select, func, over

# 给子级记录添加分区行号
child_with_row = (
    select(
        Child,
        func.row_number()
        .over(
            partition_by=Child.parent_id,
            order_by=Child.id.asc()
        ).label("row_num")
    )
    .subquery()
)

# 筛选每个父级的第一条子记录(ID最小)
min_child = (
    select(child_with_row)
    .where(child_with_row.c.row_num == 1)
    .subquery()
)

# 左连接父表与筛选后的子级
query = (
    select(Parent, min_child)
    .outerjoin(
        min_child,
        Parent.id == min_child.c.parent_id
    )
)

results = session.execute(query).all()

两种方案最终都会返回每个父级一行数据:无子级时子级字段为None,有子级时仅关联ID最小的子级记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:42:39