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)
)
两种写法的共同点都是:
- 筛选在数据库里完成
- 聚合在数据库里完成
- 关联在数据库里完成
- Python 只负责把结果集组装成需要的结构
这才是 SQL First 真正想强调的边界。