我正在Redshift:中尝试此查询
WITH RECURSIVE CTE AS
(
SELECT id
, managerid
, name
, 1 AS level
FROM users parent
WHERE name = 'Jason Ramsay'
UNION ALL
SELECT child.id
, child.managerid
, child.name
, level +1
FROM users child, users parent
WHERE child.managerid = parent.id
)
SELECT *
FROM CTE
但我一直得到这个错误:(500310(无效操作:column";电平";不存在于子项、父项中;1语句失败
我做错了什么?根据我在这里找到的文档,Redshift接受递归,这是实现它的方法:https://docs.aws.amazon.com/redshift/latest/dg/r_WITH_clause.html#r_WITH_clause-递归cte
我认为对于递归cte,cte本身必须在union all
部分中引用:
WITH RECURSIVE cte AS (
SELECT id
, managerid
, name
, 1 AS level
FROM users parent
WHERE name = 'Jason Ramsay'
UNION ALL
SELECT child.id
, child.managerid
, child.name
, level + 1
FROM cte parent -- <<-- this
JOIN users child ON parent.id = child.managerid
)
SELECT *
FROM cte
您链接到的文档中明确提到:
recursive_query一个UNION ALL查询,由两个SELECT子查询组成:
第一个SELECT子查询没有对同一个CTE_table_name的递归引用。[…]
第二个SELECT子查询在其FROM子句中引用了相同的CTE_table_name。[…]