我有一个可以这样概括的数据库:
teacher (tid, f_name, l_name);
subject (sid, title);
teacher_subject (tid, sid);
我想要的是获得教授最多科目的老师,我在这里看到了一些类似但不重复的问题,并且无法修补解决方案以达到我想要的目标,这就是我和#39;撰写:
select max(num_subs) from
(select t.f_name, t.l_name, count(t.tid) num_subs
from teacher t
join teacher_subject ts
on t.tid = ts.tid
group by t.tid)
max_subs;
但无法继续下去。我确信它有办法实现它,因为我有时候离它太近但从未到达。
答案 0 :(得分:2)
由于缺少窗口函数或允许绑定的限制条款,这在MySQL中有点尴尬,但是在这里你可以:
select *
from teacher
where tid in
(
select tid
from teacher_subject
group by tid
having count(*) =
(
select count(*)
from teacher_subject
group by tid
order by count(*) desc
limit 1
)
);
仅仅为了记录,在标准SQL中这仅仅是:
select *
from teacher t
order by (select count(*) from teacher_subject ts where ts.tid = t.tid) desc
fetch first 1 row with ties;