我需要的是选择尚未注册的可用考试(已完成),而我遇到麻烦的考试也是为了查看这些考试的时间(开始/结束)不要与学生之前注册的某些考试发生冲突。
我正在使用PostgreSQL和Clojure。 数据库是这样的:
-- exam ----------------------------------
| exam_id (PK integer) |
| exam_date (date) |
| exam_start_time (time without time zone) |
| exam_end_time (time without time zone) |
| ... |
------------------------------------------
-- student -----------------
| student_redid (PK integer) |
| ... |
----------------------------
-- student_exam --------------
| student_exam_id (PK integer) |
| student_redid (student FK) |
| exam_id (exam FK) |
| ... |
------------------------------
我用来选择可用考试的查询(使用:redid作为参数):
SELECT *
FROM exam ex
WHERE exam_id NOT IN (SELECT exam_id
FROM student_exam
WHERE student_redid = :redid)
ORDER BY ex.exam_id ASC,
ex.exam_date DESC
我需要通过验证可用的考试是否与类似于此的查询中的考试冲突来改进此查询:
SELECT *
FROM student_exam
WHERE student_redid = :redid
好吧,我现在关于使用BETWEEN,但不了解如何使用嵌套查询验证时间范围。
任何帮助将不胜感激。 谢谢!
答案 0 :(得分:1)
SELECT *
FROM exam newEx
WHERE
NOT EXIST (SELECT se.exam_id
FROM student_exam se
WHERE
se.student_redid = :redid
AND se.exam_id = newEx.exam_id)
AND NOT EXIST (SELECT se.exam_id
FROM
student_exam se inner join
exam oldEx on se.exam_id = oldEx.exam_id
WHERE
student_redid = :redid
AND newEx.exam_start_time <= oldEx.exam_end_time
AND newEx.exam_end_time >= oldEx.exam_start_time
AND newEx.exam_date = oldEx.exam_date
)
ORDER BY
newEx.exam_id ASC,
newEx.exam_date DESC