让每个老师的成绩最低的学生

时间:2015-02-26 23:06:15

标签: mysql sql group-by subquery aggregate

以下是我的表格:

师:

enter image description here

学生:

enter image description here

测试

enter image description here

老师有学生,学生参加考试。

  SELECT
    t.name as teacherName,
    s.name as studentName,
    t.id as teacherID,
    s.id as studentID,
    MIN(tt.grade) as grade
    FROM teacher t
    JOIN student s ON s.`teacher_id` = t.id
    JOIN test tt ON tt.student_id = s.id
    GROUP BY studentID;

所以我在这里得到老师 - >学生 - >最低等级(6行)

enter image description here

我想要的是

老师 - >最低年级的学生 - >等级(2行)

我可以

老师 - >每位老师的最低成绩

然后学生名字变得含糊不清,因为我没有按照那个分组......

3 个答案:

答案 0 :(得分:1)

一般的想法是加入派生表,也就是带别名的子查询。

select yourfields, temp.something, minvalue
from yourtables
join (
select something, min(value) minvalue
from yourtables
group by something
) temp on someTable.something = temp.something
and value = minvalue

你可以弄清楚细节。

答案 1 :(得分:1)

您需要制作一个子表,由老师获得最低分,然后加入。像这样:

select t.name teacher_name, s.name student_name, x.min_grade
from teacher t
join student s on t.id = s.teacher_id
join test ts on s.id = ts.student_id
join (
  select sx.teacher_id, min(tsx.grade) min_grade
  from student sx
  join test tsx on sx.id = tsx.student_id
  group by 1) x on t.id = x.teacher_id and ts.grade = x.min_grade;

答案 2 :(得分:0)

SELECT
t.name as teacherName,
s.name as studentName,
t.id as teacherID,
s.id as studentID,
tt.grade
FROM teacher t
JOIN student s ON s.`teacher_id` = t.id
JOIN test tt ON tt.student_id = s.id
JOIN (
    SELECT 
    t.id teacherID, MIN(grade) AS grade
    FROM teacher t
    JOIN student s ON s.`teacher_id` = t.id
    JOIN test tt ON tt.student_id = s.id
    GROUP BY t.id    
) j
ON j.teacherID = t.id AND j.grade = tt.grade;

arghh