MySQL使用多个表定制连接查询

时间:2013-10-30 15:50:54

标签: mysql

我正在从一个小组的每个班级中搜索一名学生。有不同的班级组,每个班级都有不同的班级,每个班级都有多个班级。见下文:

Group1 --> Class1, Class2 etc
Class1 --> GreenStudent1, GreenStudent2 etc
Class2 --> RedStudent1, RedStudent2 etc
------------------------------------------------------

SELECT 
   table1.id,
   table1.myname,
   table1.marks
   table2.studentid,
   table2.studentname
FROM table1
   INNER JOIN table3 ON table1.oldid = table3.id
   INNER JOIN table2 ON table2.studentid = table3.newid
WHERE 
   table1.classgroup = 'SCI79' 
GROUP BY table1.oldid
ORDER BY table1.marks DESC

查询中应用了不同的联接。上面提到的查询给我正确的结果,但我需要很少的修改。当前查询从每个班级返回一名学生。

我需要什么?我需要每个班级的一名学生,但只有那个有MAXIMUM

的学生
 table1.marks

所以每个班级应该有一名学生,他们的相关班级人数最多。任何人都可以建议一些解决方案或重写此查询?谢谢:))

2 个答案:

答案 0 :(得分:2)

INNER JOIN上的子查询应处理此问题:

SELECT t1.id
   ,t1.myname
   ,maxMarks.marks
   ,t2.studentid
   ,t2.studentname
FROM table1 t1
INNER JOIN table3 t3 ON t1.oldid = t3.id
INNER JOIN table2 t2 ON t2.studentid = t3.newid
INNER JOIN (
   SELECT id
      ,MAX(marks) AS marks
   FROM table1
   GROUP BY id
) maxMarks ON t1.id = maxMarks.id
   AND t1.marks = maxMarks.marks
WHERE t1.classgroup = 'SCI79'
GROUP BY t1.oldid
ORDER BY t1.marks DESC

将聚合表与MAX连接在一起本身应该将结果集过滤到每个学生及其各自的最高分。

修改

我想我误解了你原来的问题......你想要的学生只有MAX(marks)期?在这种情况下,请使用此查询:

SELECT t1.id
   ,t1.myname
   ,t1.marks
   ,t2.studentid
   ,t2.studentname
FROM table1 t1
INNER JOIN table3 t3 ON t1.oldid = t3.id
INNER JOIN table2 t2 ON t2.studentid = t3.newid
WHERE t1.classgroup = 'SCI79'
   AND t1.marks = (
      SELECT MAX(marks) AS marks
      FROM table1
   )
GROUP BY t1.oldid
ORDER BY t1.marks DESC

WHERE子句仅返回在整个表格中具有与MAX标记匹配的标记的学生。

答案 1 :(得分:0)

您可以使用max函数,例如:

where table1.marks = max(table1.marks)