如何使用NOT语法获取记录?

时间:2015-01-23 09:05:33

标签: mysql sql database

我有下一个表:教师,教师,主题和科目。每个教师都有一个主题列表

db schema

如何选择subjects不需要的faculty

注意:如果用户添加了一些新主题,那么该主题在faculty_subjects表中已经没有记录,但它应该在SELECT中显示。

总而言之 - 从存在的所有科目列表中我想知道这些教师所不需要的科目。如何实现这一目标?

我正在使用MySQL数据库。

PS。如果有更好的标题 - 请编辑。

2 个答案:

答案 0 :(得分:3)

您可以LEFT JOINFaculty_Subject使用您感兴趣的特定教员ID在连接谓词中使用,然后使用WHERE谓词过滤掉匹配的行,所以你留下了你想要的主题:

SELECT  s.id, s.Name
FROM    Subject AS s
        LEFT JOIN Faculty_Subject AS fs
            ON fs.Subject_idSubject = s.ID
            AND fs.Faculty_idFaculty = 1
WHERE   fs.id IS NULL;

注意,我通常建议使用NOT EXISTS语法:

SELECT  s.id, s.Name
FROM    Subject AS s
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    Faculty_Subject AS fs
            WHERE   fs.Subject_idSubject = s.ID
            AND     fs.Faculty_idFaculty = 1
        );

我相信的是读者更合乎逻辑,但是in MySQL LEFT JOIN/IS NULL performs better than NOT EXISTS

答案 1 :(得分:2)

SELECT name FROM Subject WHERE id NOT IN
    (SELECT FS.Subject_idSubject
        FROM Faculty_Subjects AS FS
        INNER JOIN Faculty AS F ON F.id=FS.Faculty_idFaculty
    WHERE F.name='Physics' AND FS.Subject_idSubject IS NOT NULL)