我有以下问题,我有3个表,第一个叫做我有的课程
courses| id | start | end |
--------------------------------------
1 2012-10-12 | 2012-11-12 |
students| id | available_start | available_end |
-------------------------------------------------
1 2012-10-13 2012-11-11
2 2012-11-06 2012-11-08
students_to_courses | student_id | course_id |
-------------------------------------------------
1 1
所以我试图找出哪些学生可以参加课程。因此,如果学生被添加到student_to_courses,并且日期在课程日期之间,我不需要它。 我觉得查询应该是一个子查询,但我真的不明白它们。我的查询现在看起来像这样,但无法正常工作。
SELECT s.id
FROM (`students` s)
LEFT JOIN `student_to_course` s2c ON `s2c`.`student_id` = `s`.`id`
LEFT JOIN `courses` assigned_2_course ON `s2c`.`course_id` = `assigned_2_course`.`id`
LEFT JOIN `courses` c ON `c`.`id` = 1
WHERE
(
(s.available_start NOT BETWEEN assigned_2_course.start AND assigned_2_course.end
AND
s.aviailable_end NOT BETWEEN assigned_2_course.start AND assigned_2_course.end
) OR assigned_2_course.end IS NULL)
AND
`s`.`available_start` BETWEEN c.start AND c.end
AND `s`.`available_end` <= c.end
GROUP BY `s`.`id`
ORDER BY `s`.`id` desc
这是http://sqlfiddle.com/#!2/49c11/1
现在有效,但不会删除在其他课程中分配相同日期的学生如何看到我正在尝试为课程3提供学生,该课程从02-03开始,到02-08结束,学生2在课程3中,所以未显示,学生1在课程2中,从01-03开始,到03-01结束,所以不应该可用。
任何帮助将不胜感激。
答案 0 :(得分:1)
我使用了你的SQL小提琴(但添加了另一个学生记录)http://sqlfiddle.com/#!2/246645/1
尝试这样找到所有可以参加课程3的学生,因为他们在那段时间不上课:
SELECT student.*
FROM student
JOIN course
ON course.id = 3
AND student.available_start <= course.`start`
AND student.available_end >= course.`end`
WHERE NOT EXISTS
(SELECT *
FROM student_to_course
JOIN course AS c
ON student_to_course.course_id = c.id
WHERE student.id = student_to_course.student_id
AND (course.`start` BETWEEN c.`start` AND c.`end`
OR
course.`end` BETWEEN c.`start` AND c.`end`
OR
c.`start` BETWEEN course.`start` AND course.`end`));