表“ a”有一个条目,但是不能从查询的这一部分中引用它

时间:2018-07-30 11:33:54

标签: sql postgresql

我编写了一个查询,该查询将从名为allotment的表中的现有期间生成子期间:

select a.product_id, 
daterange((lower(a.allotment_period) + concat(n.i - 1, ' days')::interval)::date, 
(upper(a.allotment_period) + concat(n.i, ' days')::interval)::date, '[]') 
from test.allotment as a
cross join(select * from generate_series(1, a.period_length)) as n(i)
where a.id = 2 

我收到此错误:

ERROR: invalid reference to FROM-clause entry for table "a" LINE 5: cross `join(select * from generate_series(1, a.period_length)... ^ HINT: There is an entry for table "a", but it cannot be referenced from this part of the query. SQL state: 42P01 Character: 250`

我发现了类似的问题SQL joins, “there is an entry for table but it cannot be referenced”,但不能解决我的问题。有人可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

问题出在from子句中。在最新版本的Postgres中,您可以使用:

from test.allotment a cross join lateral
     generate_series(1, a.period_length) n(i)

在旧版本中,您可以在generate_series()中包含select

from (select a.*, generate_series(1, a.period_length) as i
      from test.allotment a
     ) a