postgresql 如何从数组中查询NOT IN?

zf9nrax1  于 2023-02-15  发布在  PostgreSQL
关注(0)|答案(3)|浏览(137)
const friendIds = friends.rows.map((friend) => friend.friend_id);

 console.log("list", friendIds); //list [ 50, 51 ]

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

我想查询user_id不等于数组中任何项的所有用户。
由于某些原因,即使是聊天GPT也不能给予我一个很好的解决方案

vatpfxk5

vatpfxk51#

可以使用<> ALL()

SELECT * 
FROM super_user 
WHERE user_id <> ALL(ARRAY[$1])
qoefvg9y

qoefvg9y2#

通过使用ALL

SELECT * FROM 
super_user 
WHERE user_id != ALL(ARRAY[$1])

通过使用ANY

SELECT * FROM 
super_user 
WHERE NOT (user_id = ANY(ARRAY[$1]))
n9vozmp4

n9vozmp43#

在文档中,9.24. Row and Array Comparisons显示了这方面的示例:online demo

SELECT * FROM super_user WHERE not user_id = SOME(ARRAY[$1]);
SELECT * FROM super_user WHERE user_id <> ALL(ARRAY[$1]);

9.19. Array Functions and Operators中,你可以找到它也可以只unnest()数组,并与元素的结果列表进行比较,或者看看你的元素is nullarray_position()

SELECT * FROM super_user WHERE not user_id in (select * from unnest(ARRAY[$1]));
SELECT * FROM super_user WHERE array_position(ARRAY[$1], user_id) is null;

很高兴知道如果两边都是null会发生什么:

select null=any(array[1,   2]),--null, not false
       null=any(array[null,2]),--null, even though it's technically there
       1   =any(array[null,2]),--null, not false
       1   =any(array[null,1]);--true, even though there was a null to compare to

相关问题