Trung BìnhPython iconPython

N+1 Query Problem là gì? Cách giải quyết với SQLAlchemy?

N+1 problem: 1 query lấy N records, rồi N queries nữa để lấy related data.

Giải quyết bằng eager loading.

python
# N+1 problem — 1 + N queries
users = await db.execute(select(User))
for user in users.scalars():
    posts = await db.execute(  # 1 query mỗi user!
        select(Post).where(Post.user_id == user.id)
    )

# Fix: selectinload — 2 queries total
from sqlalchemy.orm import selectinload

result = await db.execute(
    select(User).options(selectinload(User.posts))
)
# 1 query lấy tất cả users + 1 query lấy posts cho tất cả user_ids

# joinedload — 1 query với JOIN (tốt khi result set nhỏ)
from sqlalchemy.orm import joinedload

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python