sql - 在不使用递归 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,但我仍然不太确定。
解决方案
这样做的选项是:
- 使用递归 CTE。
- 使用某些数据库(如 Oracle)支持的类似分层功能。
- 在脚本语言或应用程序语言中使用循环。
- 在存储过程或递归存储过程(或者可能是用户定义的函数)中使用循环。
- 显式连接或类似逻辑,如果您知道递归关系的最大深度。
递归 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。
推荐阅读
- linux - 如何安装特定版本的 libhwloc5
- powershell - 使用通配符在字符串中查找字符串 (Powershell)
- android - 如何在颤动中增加 AssetImage 中图像的大小?
- python - 将 python 与 pyinstaller 捆绑在一起,添加数据文件并使用 --onefile 标志时失败
- r - 用情节检查同方差性(汽车包)
- amazon-web-services - 如何在 S3 中解压 .gzip 文件,应用一些 sql 过滤器,并将结果作为 json 存储在 S3 中?
- reactjs - 在 React 中使用 useState 并相应地设置一个类
- sqlite - 编译错误 QSQLCIPHER driver plugin for QT undefined reference to `sqlite3_column_table_name16'
- c# - 如何在 VSTO 2019 中为功能区引发组对话启动器事件?
- firebase - 为什么变量值没有从 null 更新到给定场景中的最新值?