5

我今天遇到了一个有趣的问题(或者在我看来是这样),我认为分享它会很有成效。

我有两个具有以下结构的数据库表:

表 1:mod_class

class_id
CSD2311 
CSD2314
CSD12

表 2:m_classes_enrolled_in

student_id   class_id
5            CSD2311
5            CSD2314

因此,第一个表包含所有可能的 class_id,第二个表包含 class_id 和该班级的学生。我想创建一个学生未注册的所有课程的列表。到目前为止,左连接看起来非常好,但似乎不可能以这种方式显示它:

SELECT mod_enrolled_in.class_id 
FROM mod_enrolled_in 
WHERE student_id <> 5 
INNER JOIN mod_class 
ON mod_enrolled_in.class_id = mod_class.class_id

任何帮助将不胜感激,-D

4

5 回答 5

2

你可以通过几种方式做到这一点

1)

Select class_id from mod_class
EXCEPT
    Select class_id From m_classes_enrolled_in WHERE student_id = 5

2)

Select class_id from mod_class
Where class_id NOT IN 
      (Select class_id From m_classes_enrolled_in WHERE student_id = 5)

3)

Select class_id from mod_class m
LEFT JOIN 
    (Select class_id From m_classes_enrolled_in WHERE student_id = 5) cs
    ON m.class_id = cs.class_id
WHERE cs.class_id IS NULL
于 2013-05-03T18:29:46.967 回答
1

这就是你要找的。

SELECT mod_enrolled_in.class_id 
FROM mod_enrolled_in 
LEFT JOIN mod_class 
ON mod_enrolled_in.class_id = mod_class.class_id
WHERE class_id != 5 
AND mod_class.class_id is NULL
于 2013-05-03T18:29:36.793 回答
1

你不想LEFT JOIN mod_class这样你可以做一个反加入吗?

SELECT mod_class.class_id
FROM mod_class
LEFT JOIN mod_enrolled_in ON (mod_class.class_id = mod_enrolled_in.class_id
AND mod_enrolled_in.student_id = 5)
WHERE mod_enrolled_in.class_id IS NULL
于 2013-05-03T18:29:55.537 回答
1

尝试这个:

SELECT c.class_id
FROM mod_class c

LEFT OUTER JOIN mod_enrolled_in e
ON e.class_id = c.class_id
AND e.student_id = ?

WHERE e.student_id IS NULL;
于 2013-05-03T18:30:33.250 回答
1

用这个:-

Select class_id from mod_class
Where class_id NOT IN (Select class_id From m_classes_enrolled_in)

看到这个SQL FIDDLE

于 2013-05-03T18:40:32.347 回答