SQL中带有停止条件的递归SELECT?

Rob*_*Rob 2 sql postgresql recursion recursive-query

我的名为element 的表如下所示:

 id | successor | important
----------------------------
  1 | NULL      | 0
  2 | 4         | 1
  3 | 5         | 0
  4 | 8         | 0
  5 | 6         | 1
  6 | 7         | 0
  7 | NULL      | 0
  8 | 10        | 1
  9 | 10        | 0
 10 | NULL      | 0
Run Code Online (Sandbox Code Playgroud)

我从一个元素的 ID 开始。每个元素可能有也可能没有后续元素。因此,给定任何元素 ID,我可以从 0..n 个元素构建一个元素链,具体取决于它的后继和后继-后继,依此类推。

假设我的起始 ID 是 2。这会导致以下链:

2 -> 4 -> 8 -> 10
Run Code Online (Sandbox Code Playgroud)

现在我想问这个问题:一个特定的元素链是否至少包含一个重要的== 1的元素?

在伪代码中,无需不必要的检查即可实现这一点的函数可能如下所示:

boolean chainIsImportant(element)
{
    if (element.important == 1) {
        return true;
    }

    if (element.successor != NULL) {
        return chainIsImportant(element.successor);
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

我想这可以通过 实现WITH RECURSIVE,对吗?一旦找到具有重要 == 1 的元素,如何停止递归?

a_h*_*ame 5

这通常是通过聚合有问题的列并在 CTE 的递归部分的连接上添加条件来完成的:

with recursive all_elements as (
  select id, successor, important, array[important] as important_elements
  from elements
  where successor is null
  union all
  select c.id, c.successor, c.important, p.important_elements||c.important
  from elements c
     join all_elements p on c.successor = p.id
  where 1 <> all(p.important_elements)
)
select *
from all_elements;
Run Code Online (Sandbox Code Playgroud)

请注意,条件是“翻转”的,因为 where 子句定义了应包含的那些行。