sql语句复杂条件"加入"

时间:2014-09-04 13:29:06

标签: mysql sql

我有这3张桌子

1. course 
------------------------ 
CourseID     CourseName             
  1            English 1
  2            English 2
  3            Math 1
  4            Math 2
2. courseRequirements
------------------------
CourseID  ReqID                
   2        1
   4        3
3. studentcoursecomplete
-----------------------
CourseID   StudentID    
   1           5

我需要一个select语句执行以下操作

  1. 从课程表中显示课程名称
  2. 不要显示学生完成的课程" studentcoursecomplete"
  3. 不要显示要求学生完成的课程
  4. 显示要求学生完成的课程
  5. 此示例中的结果为

    CourseID      CourseName             
      2            English 2
      3            Math 1
    

    因为学生完成了英语1所以他无法看到它 并且他没有完成数学1 ..因此他无法看到数学2

    我的选择陈述做(1,2)
    我怎么办(3,4)
    3 - 不要显示要求学生没有完成任务的课程 4-显示有学生完成要求的课程

    SELECT course.*
    FROM course
    LEFT JOIN studentcoursecomplete ON studentcoursecomplete.CourseID = course.CourseID
    LEFT JOIN courseRequirements ON courseRequirements.CourseID = course.CourseID
    WHERE studentcoursecomplete.CourseID IS NULL 
    

2 个答案:

答案 0 :(得分:0)

你能做到的一种方法是获取用户不在的那些以及用户不能使用的那些并过滤掉总结果集中的那些......这样的事情

SELECT c.* 
FROM course c
LEFT JOIN studentcoursecomplete scc ON scc.CourseID = c.CourseID
WHERE scc.studentid = 1 
  AND scc.CourseID IS NULL
  AND c.courseid NOT IN
(   SELECT cr.courseid 
    FROM courseRequirements cr
    WHERE cr.reqid IN
    (   SELECT c.courseid 
        FROM course c
        LEFT JOIN studentcoursecomplete scc ON scc.CourseID = c.CourseID 
        LEFT JOIN courseRequirements cr ON cr.CourseID = c.CourseID 
        WHERE scc.CourseID IS NULL
          AND EXISTS
          (   SELECT 1 FROM courserequirements cr1
              WHERE cr1.CourseID <> c.CourseID
              AND cr1.reqid = c.courseid
          )
     )
)

DEMO

调整OP的答案以包含特定的用户ID ...

SELECT c.*, sc.* 
FROM semestercourses AS sc 
NATURAL LEFT JOIN course AS c 
NATURAL LEFT JOIN courserequirements AS cr
NATURAL LEFT JOIN studentcoursecomplete AS scc
WHERE sc.CourseID NOT IN 
(   SELECT CourseID 
    FROM studentcoursecomplete WHERE sid = 1
)
    AND (cr.RequirementID IS NULL OR cr.RequirementID IN 
    (   SELECT CourseID 
        FROM studentcoursecomplete WHERE sid = 1
    )
)

答案 1 :(得分:0)

SELECT c.*, sc.* FROM semestercourses AS sc
NATURAL LEFT JOIN course AS c 
NATURAL LEFT JOIN courserequirements AS cr
NATURAL LEFT JOIN studentcoursecomplete AS scc  
WHERE 
sc.CourseID NOT IN (SELECT CourseID FROM studentcoursecomplete)
    AND 
(cr.RequirementID IS NULL OR cr.RequirementID IN (SELECT CourseID FROM studentcoursecomplete))