我不明白为什么以下不会失败。子查询如何访问更高级别的不同表中的列?
drop table if exists temp_a;
create temp table temp_a as
(
select 1 as col_a
);
drop table if exists temp_b;
create temp table temp_b as
(
select 2 as col_b
);
select col_a from temp_a where col_a in (select col_a from temp_b);
/*why doesn't this fail?*/
以下失败了,正如我所期望的那样。
select col_a from temp_b;
/*ERROR: column "col_a" does not exist*/
select * from temp_a cross join (select col_a from temp_b) as sq;
/*ERROR: column "col_a" does not exist
*HINT: There is a column named "col_a" in table "temp_a", but it cannot be referenced from this part of the query.*/
我知道 LATERAL 关键字( link , link ),但我没有在这里使用 LATERAL。此外,即使在 9.3 之前的 Postgres 版本中(引入 LATERAL 关键字时),此查询也能成功。
这是一个 sqlfiddle:http://sqlfiddle.com/#!10/09f62/5/0
感谢您的任何见解。
最佳答案
虽然这个特性可能会令人困惑,但如果没有它,一些类型的查询将更难、更慢,或者无法用 sql 编写。此功能称为“关联子查询”,关联可以提供与连接类似的功能。
例如:考虑这个语句
select first_name, last_name from users u
where exists (select * from orders o where o.user_id=u.user_id)
现在这个查询将获取所有曾经下过订单的用户的姓名。现在,我知道,您可以使用与订单表的连接来获取该信息,但您还必须使用“不同的”,这在内部需要进行排序,并且执行起来可能比此查询稍差。您还可以使用分组依据生成类似的查询。
这是一个更好的示例,它非常实用,而不仅仅是出于性能原因。假设你想删除所有没有订单没有票的用户。
delete from users u where
not exists (select * from orders o where o.user_d = u.user_id)
and not exists (select * from tickets t where t.user_id=u.ticket_id)
需要注意的一件非常重要的事情是,您应该在执行此操作时完全限定或别名您的表名,否则您可能会遇到一个完全打乱查询的错字,并在返回错误数据时默默地“正常工作”。
以下是不该做的示例。
select * from users
where exists (select * from product where last_updated_by=user_id)
这看起来很好,直到您查看表并意识到表“product”没有“last_updated_by”字段而用户表有,这会返回错误的数据。添加别名,查询将失败,因为产品中不存在“last_updated_by”列。
我希望这已经为您提供了一些示例,向您展示了如何使用此功能。我一直在更新和删除语句中使用它们(以及选择——但我发现在更新和删除中经常需要它们)
关于postgresql - Postgres 子查询可以访问更高级别表中的列。这是一个错误吗?还是我不明白的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263230/