使用mysql中的连接获取所需的数据

时间:2014-01-31 17:15:03

标签: mysql join having

我的桌子:

mysql> select * from professor;
+-------+--------+--------+--------+------+
| empid | name   | status | salary | age  |
+-------+--------+--------+--------+------+
|     1 | Arun   |      1 |   2000 |   23 |
|     2 | Benoy  |      0 |   3000 |   25 |
|     3 | Chacko |      1 |   1000 |   36 |
|     4 | Divin  |      0 |   5000 |   32 |
|     5 | Edwin  |      1 |   2500 |   55 |
|     7 | George |      0 |   1500 |   46 |
+-------+--------+--------+--------+------+
6 rows in set (0.00 sec)

mysql> select * from works;
+----------+-------+---------+
| courseid | empid | classid |
+----------+-------+---------+
|        1 |     1 |      10 |
|        2 |     2 |       9 |
|        3 |     3 |       8 |
|        4 |     4 |      10 |
|        5 |     5 |       9 |
|        6 |     1 |       9 |
|        2 |     3 |      10 |
|        2 |     1 |       7 |
|        4 |     2 |       6 |
|        2 |     4 |       6 |
|        2 |     5 |       2 |
|        7 |     5 |       6 |
|        3 |     5 |       2 |
|        6 |     4 |      10 |
+----------+-------+---------+
14 rows in set (0.00 sec)

mysql> select * from course;
+----------+------------+--------+
| courseid | coursename | points |
+----------+------------+--------+
|        1 | Maths      |      5 |
|        2 | Science    |      1 |
|        3 | English    |      6 |
|        4 | Social     |      4 |
|        5 | Malayalam  |     20 |
|        6 | Arts       |     25 |
|        7 | Biology    |     20 |
+----------+------------+--------+
7 rows in set (0.00 sec)

问题是:

  

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

我试过的查询是:

select professor.name,works.courseid,works.empid,works.classid from professor
inner join works
on professor.empid=works.empid
where works.classid=10
group by works.courseid

我知道它不完整/不正确。请帮助我达到要求的结果。

2 个答案:

答案 0 :(得分:1)

select 
    professor.name, count(works.courseid)
from
    works
inner join
    professor on 
        professor.empid = works.empid 
where
    work.classid = 10
group by
    professor.name 
order by count(works.courseid) desc
limit 1

答案 1 :(得分:0)

在您的选择语句中更改此内容

 works.courseid

count(works.courseid) as courseid