无法在表中找到不在另一个表中的正确数量的值,但我可以这样做

时间:2014-10-15 14:27:33

标签: sql count

我想检索表course_id中不在表course中的takes。表格takes仅包含学生所学课程course_id。问题是如果我有:

select count (distinct course.course_id)
from course, takes
where course.course_id = (takes.course_id);

结果为85,小于表ourse_id中c course的总数,即200.结果是正确的。

但我想找到表course_id中没有的takes个数,我有:

select count (distinct course.course_id)
from course, takes
where course.course_id != (takes.course_id);

结果为200,等于表course_idcourse的数量。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

此SQL将为您提供表格中不包含在课程中的course_id的计数:

select count (*)
from course c
where not exists (select * 
                  from takes t 
                  where c.course_id = t.course_id);

您没有指定您的DBMS,但是,这个SQL非常标准,因此它应该适用于流行的DBMS。

答案 1 :(得分:0)

有几种不同的方法可以实现您的目标。我个人最喜欢的是LEFT JOIN条件。让我带你走过它:

  

事实一:您想要返回课程列表

     

事实二:你想要   过滤该列表以不在Takes表中包含任何内容。

我首先在心理上选择一系列课程:

SELECT c.Course_ID
FROM Course c

然后过滤掉我不想要的那些。一种方法是使用LEFT JOIN从第一个表中获取所有行,以及在第二个表中匹配的任何行,然后过滤掉实际匹配的行,如下所示:

SELECT c.Course_ID
FROM 
    Course c
     LEFT JOIN -- note the syntax: 'comma joins' are a bad idea.
    Takes t ON 
        c.Course_ID = t.Course_ID -- at this point, you have all courses
WHERE t.Course_ID IS NULL -- this phrase means that none of the matching records will be returned.  

另一个注意事项:如上所述,comma joins should be avoided.使用我上面演示的语法(INNER JOIN或LEFT JOIN,后跟表名和ON条件)。