返回教授10班级课程数量最多的教授的姓名

时间:2013-03-19 06:15:35

标签: mysql sql

您好我有以下数据库架构。

Professor (EMP ID,Name,Status,Salary,Age)
Course(Course ID,Course Name,Points)
Works(Course ID,EMP ID,Class ID)

我需要找到教授课程数量最多的教授的姓名,我写了以下查询,这显然是错误的。

SELECT p.empid,p.name
FROM professor p
INNER JOIN works w
ON p.empid = w.empid
AND w.classid = 10
GROUP BY p.empid,p.name
HAVING max(c.courseid)

请帮我纠正。

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT 
  p.empid
  ,p.name
  ,COUNT(w.courseid) AS coursecount
FROM 
  professor p
INNER JOIN 
  works w ON p.empid = w.empid
WHERE w.classid = 10
GROUP BY p.empid,p.name
ORDER BY COUNT(w.courseid) DESC

答案 1 :(得分:1)

尝试此查询

SELECT emp_id, max(NoOfCourse) 
from Professor p, (SELECT emp_id, count(distinct  Course_ID) as 'NoOfCourse' 
from works where class_Id = 10
group by emp_id) tbl
WHERE p.emp_id = tbl.emp_id;

答案 2 :(得分:1)

如果你知道只有一个:

select p.empid, p.name, count(courseid)
from professor p, works w
where p.empid = w.empid
  and w.classid = 10
group by p.empid, p.name
order by count(courseid) desc
limit 1;

否则:

select p.empid, p.name, count(courseid)
from professor p, works w
where p.empid = w.empid
  and w.classid = 10
group by p.empid, p.name
having count(courseid) = 
    (select max(course_count) 
     from (select count(courseid) as course_count 
           from works w2 where w2.classid = 10 group by w2.empid
          )
    );