简体   繁体   English

postgres 在子句中选择查询

[英]postgres select query in clause

Postgres is not able to compile the query (not able to identify if a column exists on the table in subquery) within in clause, I am citing a sample query Postgres 无法在 in 子句中编译查询(无法识别子查询中的表中是否存在列),我引用了一个示例查询

select * from table_a where (id is null or id not in (select distinct id from table_b)) 

This query was running fine in production, but a data defect was found and realized that there is no column id in table_b at all, even then the query was running without any compilation issues此查询在生产中运行良好,但发现数据缺陷并意识到 table_b 中根本没有列 id,即使查询运行时也没有任何编译问题

Is this a known defect or did any one encounter this issue?这是已知缺陷还是有人遇到过这个问题?

From the postgresql documentation : EXISTS (subquery) -> The subquery can refer to variables from the surrounding query, which will act as constants during any one evaluation of the subquery.来自postgresql 文档: EXISTS (subquery) -> 子查询可以引用来自周围查询的变量,这些变量将在子查询的任何一次评估期间充当常量。

The column id in the subquery is referring to table_a, not to table_b (table_b does not have a column named id).子查询中的列 id 指的是 table_a,而不是 table_b(table_b 没有名为 id 的列)。

All this queries are equivalent:所有这些查询都是等价的:

SELECT * 
FROM table_a
WHERE table_a.id IN (SELECT table_a.id)
SELECT * 
FROM table_a
WHERE table_a.id IN (SELECT id)
SELECT * 
FROM table_a
WHERE table_a.id IN (SELECT id FROM table_b)
SELECT * 
FROM table_a
WHERE table_a.id IN (SELECT table_a.id FROM table_b)

This query failed (column table_b.id does not exist):此查询失败(列 table_b.id 不存在):

SELECT * 
FROM table_a
WHERE table_a.id NOT IN (SELECT table_b.id FROM table_b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM