mysql子查询COUNT与WHERE子句混淆

时间:2018-07-28 08:38:33

标签: mysql subquery mariadb aggregate-functions

我整天都在捣碎按钮,但无法使该查询正常工作。我有3个表格的学生,课程和入学表格,显示该学生已注册的课程

查询需要检索所有至少招收2名学生的课程,并按课程数排序,最多的学生数

我想出了如何检索每个班级的招生人数,但在过滤> = 2个学生的招生方面遇到困难

-- coursetable -----------------------------

CREATE TABLE StudentTable(
studentID VARCHAR(255) NOT NULL,
firstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
DOB DATE NULL,
CONSTRAINT pk_studentTable PRIMARY KEY(studentID)
);

-- coursetable -----------------------

 CREATE TABLE CourseTable(
 courseID VARCHAR(255) NOT NULL,
 courseName VARCHAR(255) NOT NULL,
 hoursPerWeek int(11) NULL,
 startDate DATE NULL,
 CONSTRAINT pk_courseTable PRIMARY KEY(courseID)
 );

-- enrolment table --

CREATE TABLE EnrolmentTable(
    studentID VARCHAR(255) NOT NULL,
    CourseID VARCHAR(255) NOT NULL,
CONSTRAINT pk_enrolmentTable PRIMARY KEY(studentID, CourseID)
);

这是我可以显示所有班级入学情况的查询,但它显示一个只有1名学生入学的班级。我只需要显示=> 2个注册的班级

    SELECT ct.CourseName AS Course_Name, COUNT(st.studentID) AS Students_Enrolled
FROM EnrolmentTable et
INNER JOIN courseTable ct ON ct.courseID = et.courseID
INNER JOIN studentTable st ON st.studentID = et.studentID
GROUP BY et.courseID;

我需要使用子查询吗?但不确定如何

1 个答案:

答案 0 :(得分:1)

您可以使用HAVING过滤结果

SELECT ct.CourseName AS Course_Name, COUNT(st.studentID) AS Students_Enrolled
FROM EnrolmentTable et
INNER JOIN courseTable ct ON ct.courseID = et.courseID
INNER JOIN studentTable st ON st.studentID = et.studentID
GROUP BY et.courseID
HAVING Students_Enrolled> 1
ORDER BY Students_Enrolled DESC