我有下面,它返回与 Postgres 中的示例相同的结果:
WITH RECURSIVE paths AS (
-- For simplicity assume node 1 is the start
-- we'll have two starting nodes for data = 1 and 2
SELECT DISTINCT
src as node
, data as data
, 0 as depth
, src::text as path
, false as is_cycle
, ARRAY_CONSTRUCT(src) as path_array
FROM edges
WHERE src IN ( 1,2)
UNION ALL
SELECT
edges.dst
, edges.data
, depth + 1
, paths.path || '->' || edges.dst::text
, ARRAY_CONTAINS(dst::variant, path_array)
, ARRAY_APPEND(path_array, dst)
FROM paths
JOIN edges
ON edges.src = paths.node
AND edges.data = paths.data
AND NOT is_cycle
)
SELECT * FROM paths;
但是,我必须删除递归部分中的 DISTINCT,因为它在 Snowflake 中是不允许的:
SQL compilation error: DISTINCT is not allowed in a CTEs recursive term.