我正在尝试在SQL中以一般方式生成一个系列(基本上模拟嵌套循环)。
假设我们有N个下限/上限:l_1:u_1,...,l_N:u_N,我想生成一个表
col_1 | col_2 | ... | col_N
------+-------+-----+------
l_1 | l_2 | ... | l_N
l_1 | l_2 | ... | l_N+1
l_1 | l_2 | ... | l_N+2
...
l_1 | l_2 | ... | u_N
l_1 | l_2+1 | ... | l_N
l_1 | l_2+1 | ... | l_N+1
...
u_1 | u_2 | ... | u_N
------+-------+-----+------
E.g。对于1:2,2:4,结果将是
col_1 | col_2
------+-------
1 | 2
1 | 3
1 | 4
2 | 2
2 | 3
2 | 4
------+-------
可能会有一个WITH RECURSIVE查询,但很难绕过它。
我现在提出这个查询,它使用WITH RECURSION
代替generate_series
,但不确定如何将其参数化以适用于不同的边界:
WITH RECURSIVE T(n) AS (
SELECT 1 AS n
FROM (VALUES(1)) AS CN
UNION
SELECT n+1 AS n FROM T where n < 3
)
SELECT col1.n, col2.n, col1.n * col2.n
FROM T AS col1, T AS col2;