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

如何在PostgreSQL中使用NOT IN查询数组外的用户数据?

解决方案

问题原因

你写的SQL里ARRAY[$1]会把传入的friendIds数组包装成一个二维数组,比如原数组是[50,51],传入后会变成[[50,51]],导致NOT IN的条件完全不符合预期——它在和这个二维数组的元素(也就是整个子数组)做比较,而不是逐个匹配数值。

修复方法

有两种常用的正确写法:

方法1:使用 != ALL() 操作符

直接传入数组,用ALL操作符匹配数组中的所有元素:

const friendIds = friends.rows.map((friend) => friend.friend_id);

const users = await pool.query(
  "SELECT * FROM super_user WHERE user_id != ALL($1)",
  [friendIds]
);

方法2:使用 NOT (user_id = ANY($1))

这和方法1效果一致,只是写法更直观:

const friendIds = friends.rows.map((friend) => friend.friend_id);

const users = await pool.query(
  "SELECT * FROM super_user WHERE NOT (user_id = ANY($1))",
  [friendIds]
);

补充说明

如果一定要用NOT IN,需要把数组元素拆成多个参数,但这种写法不够灵活(数组长度变化时SQL语句也要改),不推荐:

const friendIds = friends.rows.map((friend) => friend.friend_id);
const placeholders = friendIds.map((_, idx) => `$${idx+1}`).join(',');

const users = await pool.query(
  `SELECT * FROM super_user WHERE user_id NOT IN(${placeholders})`,
  friendIds
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:11:12