为什么这个 Snowflake 查询不需要 LATERAL 关键字就可以工作?

Why does this Snowflake query work without requiring the LATERAL keyword?

我在 Snowflake 中有这个视图:

create or replace view foo as 
select  as id_foo,  as sales
  from (values (1,100),(2,200),(3,300));

还有这个user-defined table function

CREATE OR REPLACE FUNCTION build_aux_table ( restriction number )
  RETURNS TABLE ( aux_id number )
  AS 'select  as aux_id from (VALUES (1),(2),(3)) where aux_id = restriction';

以下查询有效,returns 3 行:

 select id_foo, baz.aux_id
  from foo
 cross join table(build_aux_table(foo.id_foo)) baz;

但是,我没想到查询会编译,因为我们要加入的 UDTF 生成的 table 依赖于第一个 table。我的理解是这种内部 table 依赖需要 LATERAL 连接,如下所示(也有效):

select id_foo, baz.aux_id
  from foo
 cross join lateral build_aux_table(foo.id_foo) baz; 

为什么没有 LATERAL 的查询有效?

Snowflake 手册中没有明确提及(至少在您链接到的地方),但标准行为是 LATERAL 关键字对于 函数 是可选的。引用 PostgreSQL manual:

Table functions appearing in FROM can also be preceded by the key word LATERAL, but for functions the key word is optional; the function's arguments can contain references to columns provided by preceding FROM items in any case.

粗体 强调我的。

恕我直言,这也很有道理。如果不是从其他表中获取参数,函数从哪里获取参数?将仅限于没有横向参考的手动输入。

代码:

select id_foo, baz.aux_id
from foo
cross join table(build_aux_table(foo.id_foo)) baz;

基本相同:

select id_foo, baz.aux_id
from foo
,table(build_aux_table(foo.id_foo)) baz;

在文档中有描述:

Calling JavaScript UDTFs in Queries

This simple example shows how to call a UDTF. This example passes literal values.

SELECT * FROM TABLE(js_udtf(10.0::FLOAT, 20.0::FLOAT));

This example calls a UDTF and passes it values from another table. In this example, the UDTF named js_udtf is called once for each row in the table named tab1. Each time that the function is called, it is passed values from columns c1 and c2 of the current row.

SELECT * FROM tab1, TABLE(js_udtf(tab1.c1, tab1.c2)) ;

Sample UDTFs - Examples with joins

Use the UDTF in a join with another table; note that the join column from the table is passed as an argument to the function.

select * 
from favorite_years y join table(favorite_colors(y.year)) c;