Select courses that are completely satisfied by a given list of prerequisites

限于喜欢 提交于 2019-12-05 17:57:41
Swapnil
SELECT  * FROM Course C LEFT JOIN Course_Prerequisites cp ON C.Id = cp.Course_FK 
         WHERE Prerequisite_FK IN (SELECT Prerequisites.Id FROM Prerequisites Where Name = 'Art' OR Name = etc etc)
 NOT EXISTS   
   (SELECT  * FROM Course C LEFT JOIN Course_Prerequisites cp ON C.Id = cp.Course_FK 
         WHERE Prerequisite_FK NOT IN (SELECT Prerequisites.Id FROM Prerequisites Where Name = 'Art' OR Name = etc etc))

I was able to solve the problem with the following query (and also learned a bit about GROUP_CONCAT along the way). The GROUP_CONCAT isn't really needed, but makes the output clearer. It also depends on the 'GROUP BY Course.id' - these can be removed if not needed. This solution performs the necessary difference of sets and selects only courses that are at least saturated by prerequisites.

I'm still quite new to this, so if there's anything that could be done better, please let me know.

SELECT Course.id, course.Name, GROUP_CONCAT(DISTINCT Prerequisite.Name) AS 'Prerequisite Name(s)'
FROM Course
  LEFT JOIN CoursePrerequisites ON Course.id = CoursePrerequisites.Course_FK
  LEFT JOIN Prerequisite ON Prerequisite.id = CoursePrerequisites.Prerequisite_FK 
WHERE NOT EXISTS 
  (SELECT 1
    FROM CoursePrerequisites 
    WHERE Course.id = CoursePrerequisites.Course_FK
      AND CoursePrerequisites.Prerequisite_FK NOT IN (SELECT Prerequisite.id FROM Prerequisite Where Name = 'Art' OR Name = 'English' OR Name = 'Psychology''))
GROUP BY Course.id;

1, SELECT Course_FK ,COUNT(1) AS Num FROM CoursePrerequisites GROUP BY Course_FK

and store the result in a temp table temp_a.

2, SELECT Course_FK ,COUNT(1) AS Num FROM CoursePrerequisites a INNER JOIN Prerequisite b ON a.Prerequisite_FK=b.Id GROUP BY Course_FK

and store the result in a temp table temp_b.

3, SELECT a.Course_FK FROM temp_a a INNER JOIN temp_b b ON a.Course_FK=b.Course_FK AND a.Num=b.Num

this will the the qualified Course's Id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!