在不使用递归 CTE 的情况下查找课程的所有先决条件

Find all the prerequisites for a course without using recursive CTE

给定一个 table:

Course code | course needed
---------------------------
2           | 1
3           | 2
4           | 3
4           | 7
5           | 4
6           | 5

我需要找到课程 5 的所有先决条件,例如。我应该得到的答案是课程代码:4, 7, 3, 2, 1.

有什么方法可以做到这一点而不需要递归 CTE?谢谢你。目前我认为唯一可行的解​​决方案是使用 join,但我仍然不太确定。

执行此操作的选项是:

  1. 使用递归 CTE。
  2. 使用类似的分层功能,某些数据库支持,例如 Oracle。
  3. 在脚本语言或应用程序语言中使用循环。
  4. 在存储过程或递归存储过程(或可能 user-defined 函数)中使用循环。
  5. 显式连接或类似逻辑,如果您知道递归关系的最大深度。

递归 CTE 是唯一一种使用标准(ish)SQL 提供通用的 single-query 问题解决方案的方法,您现在不知道先决条件图的深度。

如果你想走显式逻辑路线,一种方法是:

select t.course_needed
from t
where t.course = 5 or
      exists (select 1
              from t t2
              where t2.course_needed = t.course and
                    t2.course = 5
             ) or
      exists (select 1
              from t t2 join
                   t t3
                   on t3.course_needed = t2.course
              where t2.course_needed = t.course and
                    t3.course = 5
             ) or
      exists (select 1
              from t t2 join
                   t t3
                   on t3.course_needed = t2.course join
                   t t4
                   on t4.course_needed = t3.course
              where t2.course_needed = t.course and
                    t4.course = 5
             ) ;

Here 是一个 db<>fiddle 来说明这一点。