lateral join就是在sql中进行一个foreach循环。有两种不同的方式写lateral join。
如下,是一种简单的形式:
SELECT <columns> FROM <table reference>, LATERAL <inner subquery>;
这里的表引用可以是表、也可以是子查询。
该示例中,会迭代<table reference>中的每一行对<inner subquery>的行进行评估。就像一个foreach循环。inner subquery返回的行会被加到lateral join的结果集中。
使用lateral join的主要原因是inner subquery可以引用table reference中的行的列,并根据table reference中的列来决定inner subquery的返回值。为了帮助描述,以下是python代码模拟的lateral join:
result = [] for row1 in table_reference(): for row2 in inner_subquery(row1): result += (row1, row2)
假设表people有列(id 、age),表pets有列(id、owner_id、age)。
SELECT people_sub.id, pets_sub.id FROM (SELECT id FROM people WHERE age > 30) people_sub, LATERAL (SELECT pets.id FROM pets WHERE pets.owner_id = people_sub.id ORDER BY pets.age DESC LIMIT 1) pets_sub;
对于每个年龄超过30的人,这个查询都会评估内查询并将内查询的结果添加到整个查询。
不管你相信与否,其他写法想实现上面的查询可能会很不容易,且不高效。
另一中写lateral join的写法:
SELECT <columns> FROM <table reference> JOIN LATERAL <outer subquery> ON TRUE;
这样写的优点是你可以使用任何join修饰符(比如left join lateral)。在上面的例子中,如果还想获得没有养宠物的人,我们就需要使用 lateral left join 。通常,第一种方式就可以了。