我们有以下4个数据库表
学校
School_ID, School_Name
学生
Student_id, School_ID, Student Name
课程
Course_ID, Course_Name
Course_Student
Course_Id, Student ID
请建议一个查询,该查询返回每位学生至少注册3门科目的学校名单。
答案 0 :(得分:2)
给出架构
CREATE TABLE School
(`School_ID` int, `School_Name` varchar(7))
;
INSERT INTO School
(`School_ID`, `School_Name` )
VALUES
(1, 'SchoolA'),
(2, 'SchoolB'),
(3, 'SchoolC')
;
CREATE TABLE Student
(`Student_id` int, `School_ID` int, `Student_Name` varchar(4))
;
INSERT INTO Student
(`Student_id`, `School_ID`, `Student_Name`)
VALUES
(1, 1, 'John'),
(2, 1, 'Alex'),
(3, 2, 'Lex')
;
CREATE TABLE Course
(`Course_ID` int, `Course_Name` varchar(9))
;
INSERT INTO Course
(`Course_ID`, `Course_Name`)
VALUES
(1, 'Math'),
(2, 'Science'),
(3, 'Chemistry'),
(4, 'Physics'),
(5, 'History')
;
CREATE TABLE Course_Student
(`Course_ID` int, `Student_ID` int)
;
INSERT INTO Course_Student
(`Course_ID`, `Student_ID`)
VALUES
(1, 1),
(2, 1),
(3, 1),
(1, 2),
(1, 3),
(2, 3),
(4, 2),
(5, 2)
;
上述架构的预期输出为SchoolA
,因为它是唯一一所所有学生至少注册三门课程的学校。
SELECT SCHOOL_ID, School_Name
FROM
(
SELECT d.SCHOOL_ID, e.School_Name,e.NoOfStudents
FROM
(
SELECT a.Student_ID, a.school_ID
FROM Student a
INNER JOIN Course_Student c
ON c.Student_ID = a.Student_ID
INNER JOIN Course d
ON c.Course_ID = d.Course_ID
GROUP BY a.Student_ID, a.school_ID
HAVING COUNT(*) >= 3
) d INNER JOIN
(
SELECT b.School_ID, b.School_Name, COUNT(*) NoOfStudents
FROM Student a
INNER JOIN School b
ON a.School_ID = b.School_ID
GROUP BY b.School_ID, b.School_Name
) e ON e.School_ID = d.School_ID
GROUP BY d.SCHOOL_ID
HAVING COUNT(*) = e.NoOfStudents
) s
答案 1 :(得分:1)
select School_name from School
where School_ID not in (
select School_ID from Student
inner join Course_Student on Student.Student_id = Course_Student.[Student ID]
group by Student_ID, School_ID, Course_Id
having Count(Course_Id) < 3)
答案 2 :(得分:0)
Select School_Name, Student_Name, count(Course_Student.Course_ID) as total from School
inner join Student
on Course_Student.School_ID = Student.School_ID
inner join Course
on Student.Student_Id = Course.Student_Id
where total > 3
group by School_Name, Student_Name