首页 > 解决方案 > 在不使用递归 CTE 的情况下查找课程的所有先决条件

问题描述

给定一张桌子:

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

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

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

标签: sqlpostgresqlhierarchical-data

解决方案


这样做的选项是:

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

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

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

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
             ) ;

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


推荐阅读