supabase-postgres-best-practices - data-n-plus-one
title: Eliminate N1 Queries with Batch Loadingimpact: MEDIUM-HIGHimpactDescription: 10-100x fewer database round tripstags: n-plus-one, batch, performance, queries通过批量加载消除 N1 查询N1 查询问题指在循环中为每个项目执行一次查询。应使用数组或 JOIN 将它们合并为单个查询。错误做法N1 查询-- 第一个查询获取所有用户selectidfromuserswhereactivetrue;-- 返回 100 个 ID-- 然后是 N 个查询每个用户一个select*fromorderswhereuser_id1;select*fromorderswhereuser_id2;select*fromorderswhereuser_id3;-- ... 还有 97 个查询-- 总计101 次数据库往返正确做法单个批量查询-- 收集 ID 并使用 ANY 一次性查询select*fromorderswhereuser_idany(array[1,2,3,...]);-- 或使用 JOIN 代替循环selectu.id,u.name,o.*fromusers uleftjoinorders oono.user_idu.idwhereu.activetrue;-- 总计1 次往返应用程序模式-- 不要在应用程序代码中循环-- for user in users: db.query(SELECT * FROM orders WHERE user_id $1, user.id)-- 传递数组参数select*fromorderswhereuser_idany($1::bigint[]);-- 应用程序传递[1, 2, 3, 4, 5, ...]参考N1 查询问题