PostgreSQL key words of LATERAL

来源:互联网 发布:广州艺知艺术培训学校 编辑:程序博客网 时间:2024/06/03 19:17

文档解释:

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,name2,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,name2,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条目提供的字段“,应该好理解一些。

0 0
原创粉丝点击