简体   繁体   English

从不在另一个表中的表中选择记录

[英]Selecting records from a table not in another table

I have two tables. 我有两张桌子。

Course
course_id | name
------------------
1         | PROG
2         | ENGL
3         | SCIE

Enrollment List
ID | student_id | course_id | grade
-----------------------------------
1  | 445566     | 1         | 4.0
2  | 445566     | 2         | 2.0
3  | 778899     | 3         | 2.5

I need to query the tables such that it returns the student_id and the courses they haven't taken yet. 我需要查询表,以便它返回student_id和他们尚未学习的课程。 Outcome should be: 结果应该是:

student_id | course_id
----------------------
445566     | 3
778899     | 1
778899     | 2

I tried the query 我试过了这个问题

SELECT student_id, name FROM course c, list l WHERE NOT EXISTS(SELECT NULL FROM course c, list l WHERE c.course_id=l.course_id)

which returned zero records. 返回零记录。 How would I do this? 我该怎么做?

Simple rule: Never use commas in the FROM clause. 简单规则: 永远不要FROM子句中使用逗号。 Always use explicit JOIN syntax. 始终使用显式JOIN语法。

In any case, you need to approach this in a particular way. 无论如何,您需要以特定方式处理此问题。 Start with a list of all students and all courses. 从所有学生和所有课程的列表开始。 Then use left join or not exists to filter out the ones that are not in the list: 然后使用left joinnot exists来过滤掉不在列表中的连接:

SELECT s.student_id, c.name
FROM course c CROSS JOIN
     (SELECT DISTINCT student_id FROM list l) s
WHERE NOT EXISTS (SELECT 1
                  FROM list l2
                  WHERE c.course_id = l2.course_id and s.student_id = l2.student_id
                 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM