递归查询重复自己

时间:2017-10-31 20:05:49

标签: sql postgresql

我有一个边缘表,看起来像这样:

leftEdgeGUID,rightEdgeGUID

此表是多对多的朋友"表

我试图找到分离程度和每个节点之间的路径,以便在另一个节点中写入节点路径"表。这些数据几乎从不改变,旧的目的是实时查看这条路径和分离数据的程度。

无论如何,我的查询最终会包含我开始使用的原始边缘ID。反正是为了防止这种情况发生吗?

WITH RECURSIVE CTE AS
 (SELECT 0 AS depth, ARRAY[]::varchar[] AS parents, leftGid, rightGid, leftGid AS last_id 
  FROM entityNodes en
  INNER JOIN entities e ON e.Gid = en.leftGid
  WHERE leftGid = 'PERSON 1s GUID'
  UNION
   SELECT depth+1, array_append(parents, e.name) AS parents, en.leftGid, en.rightGid, en.rightGid AS last_id
   FROM CTE
   INNER JOIN entityNodes en ON en.leftGid = last_id
   INNER JOIN entities e ON e.Gid = en.leftGid
   WHERE depth < 6  
  )
SELECT depth, parents, eleft.Name AS leftName, eRight.name AS rightName
 FROM CTE_SD
 INNER JOIN entities eLeft ON eLeft.Gid = leftGid
 INNER JOIN entities eRight ON eRight.Gid = rightGid
WHERE eright.Name='Person 2 NAME'
ORDER by depth
;

注意:我返回的是名字而不是GUID,所以它对我来说是人类可读的,我可以快速检查理智。

我的问题是,在父母阵列中,您会再次看到第1人或第2人。

1 个答案:

答案 0 :(得分:0)

我通过检查parents数组是否等于同一数组的unnested SELECT DISTINCT版本来解决这个问题。

CREATE OR REPLACE FUNCTION array_unique (ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT DISTINCT unnest($1))
$$;

然后将此行添加到最终的WHERE子句

AND parents = array_unique(parents)