postgresql - 在类似 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 编写条件的正确方法是什么?
解决方案
为了让优化器尽其所能 - 将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];
推荐阅读
- sql - 对查询的一部分执行计算,然后将其添加到查询总数中
- javascript - 像 c# 中的 {get;set} 语法一样使用什么 javascript 语法?
- reactjs - Expo console.log 命令未显示其代码行位置
- spring-boot - H2控制台Spring Boot未打开
- spring-boot - 使用 Spring 数据从 EC2 实例访问 AWS DynamoDb 时失败
- python - 有没有办法找到这个按钮(如果它是一个按钮)并点击它?
- azure - 在 azure 数据工厂复制活动中,容错不适用于检查约束
- mongodb - mongoDb 对聚合查询的高级排序
- ruby-on-rails - 如何使用设计生成恢复密码的链接?
- c - 同时从两个csv文件读取到struct