-1

我们有以下 4 个数据库表

学校

 School_ID,  School_Name

学生

Student_id, School_ID, Student Name

课程

Course_ID, Course_Name

课程_学生

Course_Id, Student ID

请提出一个查询,该查询返回每个学生至少注册 3 个科目的学校列表。

4

3 回答 3

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
于 2012-11-16T11:12:21.473 回答
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)
于 2012-11-16T11:31:54.627 回答
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
于 2012-11-16T11:24:19.857 回答