如何使用count编写查询

时间:2015-04-25 17:02:23

标签: mysql sql database visual-studio-2012

我有两张表如下:

==================
StudentsClasses  
----------------
ID (Registration ID of the class)
StudentID (ID of student taking class)
ClassID (ID of certain class)
----------------
==================

Students
---------------
ID (ID of student)
Name (Name of student)
GradeLevelID (Grade of student)
---------------
==================

他们加入了StudentsClasses.StudentID和Students.ID。

我正在尝试编写一个查询来返回注册班次最少的学生。我的疑问是:

SELECT Students.Name, COUNT(StudentsClasses.StudentID) AS Expr1
FROM     StudentsClasses INNER JOIN
                  Students ON StudentsClasses.StudentID = Students.ID
GROUP BY StudentsClasses.StudentID, Students.Name
ORDER BY Expr1

但是,这只会返回所有ASC顺序中至少有1个班级的学生。

我知道正确答案是7名学生,0班。

如何修改我的查询以仅返回那些有0个班级的7名学生。

3 个答案:

答案 0 :(得分:0)

要招募没有课程的学生,而不是INNER JOIN,您应该在这里使用LEFT JOIN,以确保列出students表中的所有行,即使有该特定学生studentclasses中没有行。

SELECT
 s.name, count(sc.id) AS classes
FROM
 students s
 LEFT JOIN studentsclasses sc ON s.id = sc.studentid
GROUP BY s.name
HAVING count(sc.id) = 0 -- added after comment
ORDER BY count(sc.id);

或另一种方法(仅检索有0个班级的学生):

SELECT
 s.name
FROM
 students.s
 LEFT JOIN studentsclasses sc ON s.id = sc.studentid
WHERE
 sc.id IS NULL

答案 1 :(得分:0)

这应该将你的结果限制在那些拥有最小注册类数的学生身上(如果最小数目为零,那么为零,如果最小注册数为3,那么它将使用3等等。)

select      s.name,
            v.classes
from        students s
       join (
                select      s.name,
                            count(sc.id) as classes
                from        students s
                  left join studentsclasses sc
                         on s.id = sc.studentid
                group by    s.name
                order by    count(sc.id)
                limit 1
            ) v
         on s.name = v.name

答案 2 :(得分:-1)

这个问题的答案。  如何修改我的查询以仅返回那些有0个班级的7名学生。

SELECT
 s.name, count(sc.id) AS classes
FROM
 students s
 LEFT JOIN studentsclasses sc ON s.id = sc.studentid
where (SELECT count(sc.id) FROM
 students s
 LEFT JOIN studentsclasses sc ON s.id = sc.studentid)=0 
GROUP BY s.name
ORDER BY count(sc.id);