mysql子查询计数与where子句混淆

cngwdvgl  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(262)

我一整天都在捣乱按钮,但无法让这个查询工作。我有三个表,学生,课程和招生表,显示哪些班级的学生已注册
查询需要检索至少注册了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)
);

这是我可以做的查询,显示所有班级的注册人数,但它显示一个班级只有一个学生注册。我需要它只显示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;

我需要使用子查询,对吗?但不知道怎么做

v7pvogib

v7pvogib1#

你可以用 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

相关问题