加入这两个特定的表

时间:2013-05-03 18:27:00

标签: mysql join left-join

我今天遇到了一个有趣的问题(在我看来似乎如此),我认为分享它会很有效。

我有两个数据库表,其中包含以下结构:

表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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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;

答案 4 :(得分:1)

使用: -

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

请参阅此SQL FIDDLE