PostgreSQL key words of LATERAL

文档解释:

FROM子句中出现的子查询可以放在关键字LAteraL之前,这样就允许它们引用通过前置FROM条目提供的字段。(如果没有LAteraL,那么每个子查询都被认为是独立的并且不能交叉引用任何其他的FROM条目。)

这是Postgresql9.3的新增特性,第一次看到这解释,估计看不懂,看下面解释。


1. 准备好的数据。

postgres=# select * from tb10;
 id | name1 
----+-------
  1 | aa
  2 | bb
  3 | cc
(3 rows)

postgres=# select * from tb11;
 id | name2 
----+-------
  1 | dd
  3 | ee
  5 | ff
(3 rows)
2.如果没有LAteraL,那么每个子查询都被认为是独立的并且不能交叉引用任何其他的FROM条目。这句话的解释:

postgres=# select * from tb10 a inner join(select id,name2 from tb11)b on a.id=b.id;
 id | name1 | id | name2 
----+-------+----+-------
  1 | aa    |  1 | dd
  3 | cc    |  3 | ee
(2 rows)
这个是正常情况,这里有两个独立的from子查询,如果想在第二个子查询里面引用第一个查询的数据,like the following:
postgres=# select * from tb10 a inner join(select id,name2,a.name1 from tb11)b on a.id=b.id;
ERROR:  invalid reference to FROM-clause entry for table "a"
LINE 1: select * from tb10 a inner join(select id,a.name1 from...
                                                        ^
HINT:  There is an entry for table "a",but it cannot be referenced from this part of the query.
第二个子查询想引用第一个查询的name1字段,提示错误,非法访问表a的from查询

3. 使用LAteraL关键字:

postgres=# select * from tb10 a inner join lateral(select id,a.name1 from tb11)b on a.id=b.id;
 id | name1 | id | name2 | name1 
----+-------+----+-------+-------
  1 | aa    |  1 | dd    | aa
  3 | cc    |  3 | ee    | cc
(2 rows)
可以看到,使用了LAteraL关键字之后,一个查询可以访问与它并列的子查询的值。

现在来看文档的解释,”FROM子句中出现的子查询可以放在关键字LAteraL之前,这样就允许它们引用通过前置FROM条目提供的字段“,应该好理解一些。

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...