SQL从连接表中选择具有最大值的行

时间:2015-12-01 14:03:38

标签: mysql select join count max

我有这样的3个表:

讲师:

+-------------+---------+
| id-lecturer |  name   |
+-------------+---------+
| 1           | Johnson |
| 2           | Smith   |
| ...         | ...     |
| ...         | ...     |
+-------------+---------+

主题:

+------------+---------+
| id-subject |  name   |
+------------+---------+
| 1          | Math    |
| 2          | Physics |
| ...        | ...     |
| ...        | ...     |
+------------+---------+

考试:

+---------+-------------+------------+------------+
| id-exam | id-lecturer | id-subject |    date    |
+---------+-------------+------------+------------+
| 1       | 5           | 1          | 1990-05-05 |
| 2       | 7           | 1          | ...        |
| 3       | 5           | 3          | ...        |
| ...     | ...         | ...        | ...        |
+---------+-------------+------------+------------+

当我尝试做第一个SELECT:

SELECT e.`id-lecturer`, e.`id-subject`, COUNT(e.`id-lecturer`) AS `exams-num`
FROM exams e    
JOIN subjects s ON e.`id-subject`=s.`id-subject`  
JOIN lecturers l ON e.`id-lecturer`=l.`id-lecturer`  
GROUP BY e.`id-lecturer`, e.`id-subject`  

我得到了正确的答案。它显示了类似的东西:

+-------------+------------+-----------+
| id-lecturer | id-subject | exams-num |
+-------------+------------+-----------+
|        0001 |          1 |         4 |
|        0001 |          3 |         1 |
|        0001 |          4 |         1 |
|        0001 |          5 |         1 |
|        0002 |          1 |         2 |
|        0002 |          2 |         1 |
|        0002 |          4 |         1 |
|        0002 |          6 |         3 |
+-------------+------------+-----------+

现在我想只显示每位讲师的最大数量,我的代码是:

SELECT it.`id-lecturer`, it.`id-subject`, MAX(it.`exams-num`) AS `exams-number`  
FROM (  
   SELECT e.`id-lecturer`, e.`id-subject`, COUNT(e.`id-lecturer`) AS `exams-num`  
   FROM egzaminy e  
   JOIN subjects s ON e.`id-subject`=s.`id-subject`  
   JOIN lecturers l ON e.`id-lecturer`=l.`id-lecturer`  
   GROUP BY e.`id-lecturer`, e.`id-subject`) it
GROUP BY it.`id-lecturer`

输出:

+-------------+------------+--------------+
| id-lecturer | id-subject | exams-number |
+-------------+------------+--------------+
|        0001 |          1 |            4 |
|        0002 |          1 |            3 |
|        0003 |          1 |            2 |
|        0004 |          1 |            5 |
|        0005 |          2 |            1 |
+-------------+------------+--------------+

我得到每个讲师的最大值的正确数字,但是主题id不匹配,它总是占用第一行的id。如何才能使它在每一行中正确匹配这两个字段?

1 个答案:

答案 0 :(得分:0)

我猜你可以简单地使用相同的查询来处理下面的其他条件。

Select t.Lecturer_id,max(t.exams-num) from
    (SELECT e.id-lecturer as Lecturer_id, e.id-subject as Subject_id,
            COUNT(e.id-lecturer) AS exams-num
    FROM exams e    
    JOIN subjects s ON e.id-subject=s.id-subject  
    JOIN lecturers l ON e.id-lecturer=l.id-lecturer  
    GROUP BY e.id-lecturer, e.id-subject ) as t
    group by t.Lecturer_id