postgresql - Postgres 子查询可以访问更高级别表中的列。这是一个错误吗?还是我不明白的功能?

标签 postgresql

我不明白为什么以下不会失败。子查询如何访问更高级别的不同表中的列?

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/

相关文章:

database - 在 PostgreSQL 函数中返回时使用 %rowtype

sql - 使用 Rails 中的输入数字选择具有范围的对象

database - 基于工作流的系统的数据库设计

sql - 名称为 'count' 的计数列返回多行。为什么?

python - 使用 sqlalchemy 从 MySQL 数据库中读取巨大的数据集并插入到 postgres 数据库中而不会出现内存问题

postgresql - postgres : join, 分组依据,排序依据。我的查询错了吗?

postgresql - 具有动态列名的 Postgres 选择

php - Phinx - php 应用程序的数据库迁移 - postgreSQL 模式不起作用

php - 获取参数的最大值或最小值到行值postgres

sql - PSQL 查询将值生成为具有相同唯一 ID 的 json 的 json 数组