横向连接在简单的例子中失败
Lateral join fails on trivial example
我正在尝试使用横向同时创建时间序列和它的滞后:
dates as (
SELECT generate_series(max(timestamp), min(timestamp), '1 week'::interval) as ts
FROM batches,
LATERAL (SELECT lag(ts) over (order by ts)) as prev_ts
),
出于某种原因,我得到 ERROR: column "ts" does not exist
。这是怎么回事?
Table 类似 generate_series
的函数属于 FROM
子句,因为它们 return 一个 table 而不是单个值:
SELECT g.ts,
lag(g.ts) OVER (ORDER BY g.ts) AS prev_ts
FROM (SELECT max(timestamp) AS lts, min(timestamp) AS uts
FROM batches) AS subq
CROSS JOIN LATERAL
generate_series(lts, uts, '1 week'::interval) as g(ts);
你得到错误不是因为你在 SELECT
列表中使用了 generate_series
,这是允许的,但可能有意想不到的语义,而是因为 ts
被定义为别名SELECT
列表而不是 FROM
。请记住,FROM
是在 之前 SELECT
列表计算的,因此您不能在前者中使用在后者中创建的别名。
我正在尝试使用横向同时创建时间序列和它的滞后:
dates as (
SELECT generate_series(max(timestamp), min(timestamp), '1 week'::interval) as ts
FROM batches,
LATERAL (SELECT lag(ts) over (order by ts)) as prev_ts
),
出于某种原因,我得到 ERROR: column "ts" does not exist
。这是怎么回事?
Table 类似 generate_series
的函数属于 FROM
子句,因为它们 return 一个 table 而不是单个值:
SELECT g.ts,
lag(g.ts) OVER (ORDER BY g.ts) AS prev_ts
FROM (SELECT max(timestamp) AS lts, min(timestamp) AS uts
FROM batches) AS subq
CROSS JOIN LATERAL
generate_series(lts, uts, '1 week'::interval) as g(ts);
你得到错误不是因为你在 SELECT
列表中使用了 generate_series
,这是允许的,但可能有意想不到的语义,而是因为 ts
被定义为别名SELECT
列表而不是 FROM
。请记住,FROM
是在 之前 SELECT
列表计算的,因此您不能在前者中使用在后者中创建的别名。