开发者

Help with SQL join combined with lots of subqueries

I have limited experience with joins, and this puzzle has me stumped.

Here are the relevant tables from my mysql database:

  • A students table
  • A sections table describing sections of a given course
  • A map table that creates a many-to-many relationship between sections and students
  • An exams table describing exams
  • A many-to-many map table between exams and sections
  • An exam_schedules table that describes the days on which exams may be taken. There is a one-to-many relationship between exams and exam_schedules.

My Goal: retrieve all students that are enrolled in the sections that have exams scheduled on a given date. Also get exam scheduling information f开发者_如何学Goor each test that the student has to take on the given date. It is desirable to have a row in the result set for each student<->exam_schedule pair.

I have a query that accomplishes the first half of my goal (it has a lot of subqueries):

SELECT * FROM `students` WHERE `id` IN
    (SELECT `student_id` FROM `sections_students` WHERE `section_id` IN
        (SELECT `section_id` FROM `sections_exams` WHERE `exam_id` IN
            (SELECT `exam_id` FROM `exam_schedules` WHERE `date` = DATE('$date') AND `exam_id` IN
                (SELECT `id` FROM `exams` WHERE `isAutoSignup` = 1))))

What I can't figure out is how to incorporate a join into that in order to accomplish the second half of my goal. My every attempt has produced a syntax error. Please, can anyone point me in the right direction? Thanks in advance!


you can do all that with joins and thus obtaining exam_schedules in the way:

SELECT s.*, es.*
  FROM students s
JOIN sections_students ss on s.id          = ss.student_id
JOIN sections_exams    se on se.section_id = ss.section_id
JOIN exam_schedules    es on es.exam_id    = se.exam_id and date = DATE('$date')
JOIN exams             e  on e.id          = es.exam_id and isAutoSignup = 1


Here is a shot:

SELECT S.Student_name, E.Exam_name, ES.date
FROM students S
LEFT OUTER JOIN SECTIONS_STUDENTS SS
  ON SS.student_id = S.stuent_id
LEFT OUTER JOIN SECTIONS_EXAMS SE
  ON SE.section_id = SS.section_id
LEFT OUTER JOIN  EXAMS E
  ON E.exam_id = SE.exam_id
LEFT OUTER JOIN EXAM_SCHEDULES ES
  ON ES.exam_id =E.exam_id
WHERE 1=1
  AND E.isAutoSignup = 1
  AND ES.Date = DATE('$date')

Joins are like writing out your thoughts.

I want the students and I want students in sections and I want the exams for the sections and I want the schedules for the exams filter on exam schedules, and exams in this way...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜