2012-11-16 49 views
-1

我们有以下4个数据库表应该查询什么?

学校

School_ID, School_Name 

学生

Student_id, School_ID, Student Name 

Course_ID, Course_Name 

Course_Student

Course_Id, Student ID 

请建议的查询返回的学校,其每名学生报名参加了至少3个科目列表。

+5

请**先告诉我们你的努力!** [你尝试过什么?](http://www.whathaveyoutried.com) –

+0

这是家作品吗? – danihp

+0

哦,不,不,这只是非常巨大的查询的一部分(我正在处理其他部分:视图,触发器和storedProcedure)。这是一个迫切的事情,是我想从我的计算器的朋友那里寻求帮助:) ....我改变了实体的名称和他们的关键,使其易于理解(我认为是因为实体名称,我认为这是一项作业) –

回答

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,因为它是有谁是ATLEAST三门课程招收的所有学生的唯一一所学校。

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

这只会返回**至少有一名学生** **参加3门或更多课程的学校。每所学校需要额外支付相当于该学校的学生总数。 – CyberDude

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 
+0

请建议查询返回**学校列表** – CyberDude

+0

这可能会返回学校,其中一些学生注册少于三门课程。 – geekchic

+1

实际上,我认为它会返回一个错误:#1054 - 'where子句'中的未知列'total' – Jocelyn

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) 
相关问题