SQL集合划分

时间:2013-12-18 03:38:52

标签: mysql sql database

我目前正在攻读一个决赛,之前考试的一个研究问题如下:

您有以下架构:
学生Snum:整数,Sname:字符串,Major:字符串,Class:字符串,Age:字符串)<登记/> 课程Cname:字符串,Meets_at:时间,Room:字符串,Fid:整数)
教师Fid:整数,Fname:字符串,Deptid:整数)
已注册Snum:整数,Cname:整数)

我遇到的问题是:

  

&#34;找到在每个房间教授的所有教职员工的姓名   有些班级会见&#34;

这是我到目前为止所做的:

SELECT DISTINCT( Fname )
FROM (FACULTY NATURAL JOIN COURSE AS C1), COURSE AS C2
WHERE C1.Room = C2.Room
GROUP BY Fname,C2.Cname
WHERE COUNT(C1.Room) = (SELECT COUNT(DISTINCT(Room)) 
                        FROM COURSE
                        WHERE Cname = C2.Cname);

我认为我走在正确的轨道上,但我不确定这是否正确。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

是的我认为你在正确的轨道上采取的策略是将每位教员的数量与课程表上不同房间的数量相匹配。

尝试以下查询:

SELECT DISTINCT F.Fname
FROM 
Faculty AS F
INNER JOIN
    (SELECT Fid, COUNT(DISTINCT Room) AS cnt FROM Course
    GROUP BY Fid
    ) rooms_per_faculty 
    ON F.Fid = rooms_per_faculty.Fid
INNER JOIN
    (SELECT COUNT(DISTINCT Room) AS cnt FROM Course) rooms_that_meet 
    ON rooms_per_faculty.cnt = rooms_that_meet.cnt

(可能有助于提供一些数据,在下面的例子中,只有Dr.4符合标准 - 在所有三个课程室教学 - A,B,C)

create local temporary table course(Room varchar(1), Fid int);
create local temporary table faculty(Fid int, Fname varchar(3));
insert into faculty
    select 1, 'DR1'
union select 2, 'DR2'
union select 3, 'DR3'
union select 4, 'DR4';

insert into course
    select 'A',1
union select 'B',1
union select 'A',2
union select 'C',3
union select 'B',4
union select 'A',4
union select 'C',4;