HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

07-数据库别拖后腿:迁移命名、约束约定和 SQL 优先

第 20 / 22 段:N+1:SQL First 最典型的反例

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、SQLAlchemy、PostgreSQL、Alembic

N+1:SQL First 最典型的反例(续)

stmt = (
    select(Post, User.username.label("author_name"))
    .join(User, User.id == Post.author_id)
    .order_by(Post.created_at.desc())
)
rows = await db.execute(stmt)

result = [
    {
        "id": post.id,
        "title": post.title,
        "author_name": author_name,
    }
    for post, author_name in rows.all()
]

这些例子的共同点都不是“SQL 写得更复杂”,而是: 数据库一次把该做的关联和统计做完,Python 不再扮演手工数据拼装器的角色。

对于更复杂的统计场景,也可以把预聚合放进子查询:

post_count_subq = (
    select(Post.author_id, func.count(Post.id).label("post_count"))
    .group_by(Post.author_id)
    .subquery()
)

stmt = (
    select(User, post_count_subq.c.post_count)
    .outerjoin(post_count_subq, post_count_subq.c.author_id == User.id)
)

两种写法的共同点都是:

这才是 SQL First 真正想强调的边界。