一道数据库面试题

一道数据库面试题

课程表A : aid,表示每个课程的ID
学生表B : bid,表示每个学生的ID
教师表C : cid,表示每个教师的ID
课程-学生表D : aid, bid,表示某个学生选了某个课程
课程-教师表E : aid, cid,表示某个老师教了某个课程

二元组(x,y),表示被x个老师教的学生有y个
例如被5个老师教的学生有100个,被6个老师教的学生有200个等等

使用sql语句求出所有的(x,y)
例如:
(1, 40)
(2, 50)
(4, 100)

select cnt,count(distinct bid) from ( -- cnt teacher(s), how many students
select bid,count(distinct cid) cnt  -- one student have many teacher
 from
(select E.cid,D.bid from E left join D on E.aid = D.aid) t
group by bid) tt
group by cnt;
原文地址:https://www.cnblogs.com/shenfeng/p/select_student_teacher_relation.html