这是一个错误吗? Postgres“IN”子句接受不在子查询表中的列名 (请注意,“product_name”不是inner_table 中的有效列,但对于“outer”表来说是。
select product_name
from scratch.outer_table
where product_name in (
select product_name
from scratch.inner_table
);
product_name
--------------
dog door
gerbil wheel
(2 rows)
但是如果我直接尝试,它会正确地注意到不正确的列名称:
select product_name from scratch.inner_table;
错误:列“product_name”不存在
\d scrap.inner_table;
表“scratch.inner_table”:
Column | Type | Collation | Nullable | Default
----------------+---------+-----------+----------+---------
product_code | text | | |
product_number | integer | | |
caryoil=# \d scrap.outer_table;
表“scratch.outer_table”:
Column | Type | Collation | Nullable | Default
--------------+---------+-----------+----------+---------
product_name | text | | |
product_id | integer |
我修复了我的实际代码以使用正确的列名称,但我仍然很好奇为什么 Postgres 允许通过无效的列名称。 如果我用 CTE 尝试它,它(正确地)会抛出错误。 我还注意到,只有当我使用“外部”表中的有效列名时,这才有效。这是“IN”子句只是一系列“or”子句的语法糖这一事实的结果吗?
检查是否有任何列名有效,但它无效——必须是外部表中的列名: select Product_name from scrap.outer_table where Product_name in (select foo from scrap.inner_table); 错误:列“foo”不存在
您的查询相当于
select o.product_name
from scratch.outer_table o
where o.product_name in (
select o.product_name
from scratch.inner_table i
);
你看出问题出在哪里了吗?这不是一个错误,而是 postgres 解释该查询的方式。