获得MySQL的最佳射手

时间:2012-10-30 08:20:49

标签: mysql sql

我有简单的表格:

ID    Score
1     90
2     85
3     96
4     96
5     73

我想获得最佳射手,所以我使用了最大功能:

select max(s.score) as score,
    s.id
from student_score as s

结果:

score    id
96       1

问题是,有两名得分手,我将如何获得所有最佳得分手?

4 个答案:

答案 0 :(得分:5)

子查询从表student_score获得最高分,其结果将用于比较WHERE子句。

SELECT a.*
FROM student_score a
WHERE Score = 
(
    SELECT MAX(Score)
    FROM student_score
)

答案 1 :(得分:3)

select s.score, s.id
from student_score as s
where
    s.score in 
    (
        select max(t.score)
        from student_score as t
    )

如果您希望子查询可重用,请尝试使用

select s.score, s.id, m.score
from student_score as s
    cross join (select max(t.score) as score from student_score as t) as m
where s.score = m.score

SQL FIDDLE EXAMPLE

答案 2 :(得分:2)

试试这个:

将您的查询用作子查询,以从实际表中选择分数

select * 
from  student_score 
where score in
 (
    select max(score)
    from   student_score )


SQL Fiddle demo

答案 3 :(得分:1)

Max是一个聚合函数,只返回一行。最简单的方法是发出一个子查询:

SELECT * FROM student_score
WHERE score = (
    SELECT MAX(score) FROM student_score
)

如果你有很多行,请确保你有得分指数。