MySql查询:如何编写内部选择连接查询

时间:2016-05-04 10:30:49

标签: mysql sql

我有五张桌子:1。课程2.departmetns 3.students 4. enroll_courses 5.results

Departments has id
Courses has id, department_id
Students has id,department_id
Enroll_courses has id, courses_id,students_id
Results has id, courses_id,students_id

我必须选择在enroll_courses表中但不在结果表中的courses.name。

我写了查询,我无法得到确切的答案。如果有人可以帮我找到解决方案。

查询:

SELECT courses.name 
FROM courses 
    JOIN departments ON courses.department_id = departments.id 
    JOIN students ON departments.id = students.department_id 
WHERE students.id = 9
  AND courses.id IN (SELECT course_id FROM enroll_courses)

1 个答案:

答案 0 :(得分:1)

由于你没有提供任何DDL's,它有点盲目拍摄,但我认为results表有一个course_id列,如果没有,则将其更改为关系。您可以使用EXISTS()NOT EXISTS()

执行此操作
SELECT courses.name 
FROM courses 
    JOIN departments ON courses.department_id = departments.id 
    JOIN students ON departments.id = students.department_id 
WHERE EXISTS(SELECT 1 FROM enroll_courses ec WHERE ec.course_id = courses.id)
  AND NOT EXISTS(SELECT 1 FROM results r WHERE r.course_id = courses.id)
  AND students.id =9