无法在 Redshift 上将 JOIN 与generate_series 一起使用

问题描述 投票:0回答:3
当在简单的 select 语句中使用时,Redshift 上的generate_series 函数按预期工作。

WITH series AS ( SELECT n as id from generate_series (-10, 0, 1) n ) SELECT * FROM series; -- Works fine

一旦我添加 JOIN 条件,redshift 就会抛出

com.amazon.support.exceptions.ErrorException:函数 generate_series(整数,整数,整数)“不支持”

DROP TABLE testing; CREATE TABLE testing ( id INT ); WITH series AS ( SELECT n as id from generate_series (-10, 0, 1) n ) SELECT * FROM series S JOIN testing T ON S.id = T.id; -- Function "generate_series(integer,integer,integer)" not supported.

红移版本

SELECT version(); -- PostgreSQL 8.0.2 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.4.2 20041017 (Red Hat 3.4.2-6.fc3), Redshift 1.0.1485

是否有任何解决方法可以使这项工作正常进行?

sql amazon-redshift
3个回答
4
投票

generate_series

。它只能在领导节点上独立工作。

解决方法是对任何具有足够行数的表使用

row_number

with series as ( select (row_number() over ())-11 from some_table limit 10 ) ...

此外,这个问题已经被问过多次了


2
投票
您是对的,这在 Redshift 上不起作用。 请参阅

此处

最简单的解决方法是预先使用该表中的值“手动”创建一个永久表,例如您可以在该表上包含 -1000 到 +1000 的行,然后从该表中选择范围,

所以对于你的例子,你会有类似的东西

WITH series AS ( SELECT n as id from (select num as n from newtable where num between -10 and 0) n ) SELECT * FROM series S JOIN testing T ON S.id = T.id;

这对你有用吗?

或者,如果您无法事先创建表格或不想这样做,您可以使用类似的东西

with ten_numbers as (select 1 as num union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) ,generted_numbers AS ( SELECT (1000*t1.num) + (100*t2.num) + (10*t3.num) + t4.num-5000 as gen_num FROM ten_numbers AS t1 JOIN ten_numbers AS t2 ON 1 = 1 JOIN ten_numbers AS t3 ON 1 = 1 JOIN ten_numbers AS t4 ON 1 = 1 ) select gen_num from generted_numbers where gen_num between -10 and 0 order by 1;
    

0
投票
使用 redshift 生成行的正确方法是使用WITH RECURSIVE CTE,如下所示:

with recursive t(n) as ( select 0::integer union all select n+1 from t where n <= 100 ) select n*2 as two_times_n from t;
您可以与任何您想要的真实桌子连接。

请参阅

https://docs.aws.amazon.com/redshift/latest/dg/r_WITH_clause.html

© www.soinside.com 2019 - 2024. All rights reserved.