SQL 2003 标准 里有提到 lateral 关键字.
PG 数据库 在9.3 中引入了这个关键字, 他的用途就是可以在子查询中 跟外面的表实现关联.
例如:
[code]
^
postgres=# create table abc(id int , b int , c int) ;
CREATE TABLE
postgres=# insert into abc values(1,1,1) ,(1,2,1),(1,3,2),(2,3,2),(2,3,3),(3,4,2),(3,4,4) ;
INSERT 0 7
postgres=# select * from abc;
id | b | c
----+---+---
1 | 1 | 1
1 | 2 | 1
1 | 3 | 2
2 | 3 | 2
2 | 3 | 3
3 | 4 | 2
3 | 4 | 4
(7 rows)
我们查询 每个id 以及这个id 对应的B 字段的平均值 .
postgres=# select id, b ,c ,avg_s
from abc s1 ,
lateral (
select avg(b) as avg_s from abc s2 where s1.id=s2.id) ss ;
id | b | c | avg_s
----+---+---+--------------------
1 | 1 | 1 | 2.0000000000000000
1 | 2 | 1 | 2.0000000000000000
1 | 3 | 2 | 2.0000000000000000
2 | 3 | 2 | 3.0000000000000000
2 | 3 | 3 | 3.0000000000000000
3 | 4 | 2 | 4.0000000000000000
3 | 4 | 4 | 4.0000000000000000
(7 rows)
同样的sql 我们用以前的做法的比如用with 语法:
^
postgres=# with ss as (select id,avg(b) as avg_s from abc group by id )
select s1.id,s1.b ,s1.c ,s2.avg_s from abc s1 , ss s2 where s1.id =s2.id ;
id | b | c | avg_s
----+---+---+--------------------
1 | 1 | 1 | 2.0000000000000000
1 | 2 | 1 | 2.0000000000000000
1 | 3 | 2 | 2.0000000000000000
2 | 3 | 2 | 3.0000000000000000
2 | 3 | 3 | 3.0000000000000000
3 | 4 | 2 | 4.0000000000000000
3 | 4 | 4 | 4.0000000000000000
(7 rows)
[/code]
用with 语法可以实现同样的功能, sql 的编写会稍微复杂一点,
LATERAL 关键字的就是解决了这个问题,
但是也带来了另一个问题,会导致sql 语句所表达的逻辑性 比较难理解.
比如我们一看with 的语句,我们知道是求 id 的平均值了,
看lateral 的语法,我们需要考虑下,这个是做什么用, 当然了了,如果习惯了,应该也不存在问题.
但是需要思考一下. 用在更复杂的sql 里,他的用处应该更大一些.
根据能量守恒定律 , 虽然写法简单了,但是运算量,并没有减少多少.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/133735/viewspace-1869548/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/133735/viewspace-1869548/