首页 > 解决方案 > 在类似 WHERE NOT IN 的子句中使用数组变量

问题描述

我已将数组变量声明为

select array(select "account_id" from [some where clause]) as negateArray;

请注意,我返回一列。现在我需要在另一个 WHERE 子句中使用它,这应该意味着:如果 account_id 与 negateArray 中的任何一个匹配,则不要包含数据

我写了类似的东西

select * from [some other where clause] WHERE (account_id NOT IN ANY(negateArray));

但我收到语法错误。为 PostgreSQL 编写条件的正确方法是什么?

标签: postgresql

解决方案


为了让优化器尽其所能 - 将not in条件转换为left [outer] join. 这是一个等效的纯 SQL 版本重写:

   select  t2.*
     from  outer_table t2 
left join  (select account_id from inner_table where [some where clause on inner_table]) t1
       on  t2.account_id = t1.account_id 
    where  [some other where clause on outer_table]
      AND  t1.account_id IS NULL;

t1.account_id IS NULL做这项not in工作。

使用和反转条件编辑
等效但更短(并且可能更有效) :[inner] join

select  t2.*
  from  outer_table t2 
  join  (select account_id from inner_table where NOT [some where clause on inner_table]) t1
    on  t2.account_id = t1.account_id 
 where  [some other where clause on outer_table];

推荐阅读