正确使用Not In子句

时间:2016-05-02 08:28:22

标签: php mysql sql

这里的情景是:

我有4张桌子

  1. Course
  2. Student
  3. Department
  4. EnrollCourse
  5. 当学生要参加课程时,课程列表应该从课程表中下拉。但是已经在enroll_courses表中的course_id不应该加载到该课程下拉列表中。因为学生不能注册单个课程2次。在这里,我使用not in操作,它将检索不在enroll_courses表中的course_id列表。

    但是我收到了以下错误信息:

      

    您的SQL语法有错误;检查手册   对应于您的MariaDB服务器版本,以获得正确的语法   near' enroll_courses.course_id LIMIT 0,25'在第6行

    这是查询:

    SELECT students.name, students.email,departments.name as d_name,
            courses.name as c_name
            FROM students JOIN departments on students.department_id=departments.id 
            JOIN courses on departments.id = courses.department_id
            LEFT JOIN enroll_courses on enroll_courses.course_id=courses.id 
            WHERE courses.id NOT IN (enroll_courses.course_id) AND students.id=8
    

    有谁能帮我找到解决方案?

2 个答案:

答案 0 :(得分:2)

试试这个,

SELECT  students.name ,
        students.email ,
        departments.name AS d_name ,
        courses.name AS c_name
FROM    students
        JOIN departments ON students.department_id = departments.id
        JOIN courses ON departments.id = courses.department_id
        JOIN enroll_courses ON enroll_courses.course_id = courses.id
WHERE   students.id = 8
        AND courses.id NOT IN ( enroll_courses.course_id );

答案 1 :(得分:1)

有多种方法可以获得所需的结果,这与原始查询非常接近:

SELECT  students.name ,
        students.email ,
        departments.name AS d_name ,
        courses.name AS c_name
FROM    students
JOIN departments
  ON students.department_id = departments.id
JOIN courses
  ON departments.id = courses.department_id
WHERE students.id = 8   
-- up to here it's all possible courses

-- now remove already enrolled courses
  AND courses.id NOT IN  
   (
     SELECT course_id
     FROM enroll_courses
     WHERE student_id = 8
   )

或相关版本:

  AND courses.id NOT IN  
   (
     SELECT course_id
     FROM enroll_courses
     WHERE student_id = students.student_id
   )

或不是EXISTS:

  AND NOT EXISTS 
   (
     SELECT *
     FROM enroll_courses
     WHERE student_id = students.student_id
       AND course_id = courses.course_id
   )