查询每一门课的间接先行课(即先行课的先行课)。
时间: 2024-01-18 10:03:23 浏览: 140
查课表
假设有两张表:课程表(courses)和先行课表(prerequisites),其中课程表中保存了每门课程的信息,包括课程编号和课程名称,先行课表中保存了每门课的先行课信息,包括先行课编号和课程编号,则可以使用以下 SQL 语句查询每一门课的间接先行课(即先行课的先行课):
```
WITH RECURSIVE indirect_prerequisites AS (
SELECT
course_id,
prerequisite_id
FROM
prerequisites
UNION ALL
SELECT
indirect_prerequisites.course_id,
prerequisites.prerequisite_id
FROM
indirect_prerequisites
INNER JOIN prerequisites ON indirect_prerequisites.prerequisite_id = prerequisites.course_id
)
SELECT
courses.course_id,
courses.course_name,
indirect_prerequisites.prerequisite_id,
indirect_prerequisites.course_id AS indirect_prerequisite_id
FROM
courses
LEFT JOIN indirect_prerequisites ON courses.course_id = indirect_prerequisites.course_id
ORDER BY
courses.course_id ASC,
indirect_prerequisites.course_id ASC;
```
其中,使用 WITH RECURSIVE 关键字和递归的方式,先查询出每个课程的直接先行课和间接先行课,然后再用 LEFT JOIN 关键字将课程表和先行课表进行关联,得到每门课的间接先行课,并用 SELECT 子句选择需要查询的字段,最后用 ORDER BY 子句对结果进行排序,即可得到每一门课的间接先行课(即先行课的先行课)。
阅读全文