douhuangzhi0707 2016-05-02 08:28
浏览 149
已采纳

正确使用Not In子句

Here, the scenario is:

I have 4 tables

  1. Course
  2. Student
  3. Department
  4. EnrollCourse

While a student going to enroll a course a list of courses should be in dropdown from courses table. But course_id which are already in enroll_courses table shouldn't load in that courses dropdown. Because a student can't register single course 2 times. Here I'm using not in operation which will retrieve list of course_id which are not in enroll_courses table.

But I'm getting following error for the query:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'enroll_courses.course_id LIMIT 0, 25' at line 6

Here is query:

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

Anyone who can help me to find the solution?

  • 写回答

2条回答 默认 最新

  • dpdhnd3577 2016-05-02 11:05
    关注

    There are several ways to get the desired result, this is close to your original query:

    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
       )
    

    Or a Correlated version:

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

    Or NOT EXISTS:

      AND NOT EXISTS 
       (
         SELECT *
         FROM enroll_courses
         WHERE student_id = students.student_id
           AND course_id = courses.course_id
       )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题