如何在mysql中选择两个唯一的字段值

时间:2013-11-19 20:35:40

标签: mysql sql

我有一个考试成绩表,其中包含考试,级别和用户获得的分数。正如您在表中看到的那样

id     examid   level   points
228    2        1       90     
229    3        1       85     
230    3        1       65  *   
227    1        1       60  *
231    2        2       20 
232    1        1       80

对于每项独特考试,将选择最高分。 我想为每个独特的考试和独特的水平选择具有最高分的行。行232的行数大于行227的行数,232行的结果比229更高。另一个是行230,其行数大于id examid level points 228 2 1 90 229 3 1 85 231 2 2 20 232 1 1 80

选择我的结果集后应如下所示:

SELECT * FROM results WHERE userid = 20 GROUP BY examid ORDER BY points  

我尝试查询

id     examid   level   points
227    1        1       60  
229    3        1       85  
228    2        1       90  

仅产生

{{1}}

3 个答案:

答案 0 :(得分:2)

如果您想要所有字段(包括id),您可以重新加入表格。

SELECT results.*
FROM results
JOIN (
  SELECT examid, level, max(points) AS points
  FROM results
  GROUP BY examid, level ) maxPoints
ON results.examid = maxPoints.examid
  AND results.level = maxPoints.level
  AND results.points = maxPoints.points 

答案 1 :(得分:2)

SELECT examid, level, MAX(`points`)
FROM score
GROUP BY examid, level
ORDER BY id

请参阅SQLFiddle here

答案 2 :(得分:1)

如果您不需要ID,可以使用简单的GROUP BY

SELECT examid, level, MAX(points) AS points
FROM tablename
GROUP BY examid, level