【问题标题】:CTE SQL query is recursing in two directionsCTE SQL 查询在两个方向上递归
【发布时间】:2012-07-11 08:59:39
【问题描述】:

我正在使用 Postgres 9.1,并且我有一个表,其中包含家谱层次结构。此表称为父母,其中有两个外键,一个用于父级,一个用于关系中的子级。以下 SQL 查询(大部分是从 Postgres 文档中窃取的)可以工作,但会向上和向下遍历树:

with recursive temp(child, parent, depth, path, cycle) as
        (select child, parent, 1, array[child], false
         from parents
         where parent = 149

         union all

         select parents.child, parents.parent, temp.depth + 1, path || parents.child, parents.child = any(path)
         from temp, parents
         where parents.child = temp.parent)
    select distinct c1.name as child_name, c2.name as parent_name
    from temp
    join people c1 on temp.child = c1.id
    join people c2 on temp.parent = c2.id;

Parent 149 是遍历的根节点。

输出有 149 个子代和所有代的祖先。理想情况下,查询将沿家谱下降,没有祖先的代。

【问题讨论】:

  • 也许把where parents.child = temp.parent改成where parents.parent = temp.child

标签: sql postgresql common-table-expression postgresql-9.1


【解决方案1】:

免责声明:在我意识到@wildplasser 在他们对该问题的评论中具有相同的already suggested 之前,此答案已被接受。 (不是想盗用别人的想法,抱歉。)

如果您只想构建给定父代的后代,则应更改此条件

parents.child = temp.parent

到这里

temp.child = parents.parent

因为在下一次迭代中应该将 temp 子代视为父代(即与 parents.parent 匹配)。

【讨论】:

  • 这基本上是 wildplasser 评论的副本,没有给予信用。
  • 啊,真丢人。我希望我当时看到它!我的意思是,我意识到很难相信我没有。我想我现在就添加功劳。
  • 没关系。无论如何,这太微不足道了;-)
  • @wildplasser:谢谢,你很友善。但我想让你知道,无论是否微不足道,我仍然会试图说服你发表你的评论作为答案。 :)
猜你喜欢
  • 2016-01-25
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多