我正试图从学生表中获得前5名。 表看起来像那样。
table: student
id name score
1 a 100
2 b 100
3 c 90
4 d 87
5 e 85
6 f 88
7 g 83
9 h 92
如果我这样做
select name,score from student order by score desc limit 5
a 100
b 100
h 92
c 90
f 88
但是,我希望看到这个结果
a 100
b 100
h 92
c 90
f 88
d 87
我试图找出重复得分为第一 有解决方案吗 提前谢谢。
答案 0 :(得分:3)
SELECT s.*
FROM student AS s
JOIN
( SELECT DISTINCT score
FROM student
ORDER BY score DESC
LIMIT 5
) AS lim
ON s.score = lim.score
ORDER BY s.score DESC ;
答案 1 :(得分:2)
这是一种方式:
select s.*
from student s
where s.score >= (select score
from (select distinct score from student order by score desc limit 5) s
order by score
limit 1
)
这会在最内部子查询中按降序获得分数。它将此限制为五个不同的分数。然后,它找到最小值,并返回具有此分数或更高分数的所有行。
答案 2 :(得分:1)
尝试使用GROUP BY
:
SELECT
score
COUNT(*) AS score_count
FROM
student
GROUP BY
score
ORDER BY
score desc
LIMIT 5
答案 3 :(得分:0)
这里是sql fiddle
SELECT s.id, s.name,s.score FROM tbl_student AS s INNER JOIN (SELECT * FROM tbl_student ORDER BY score DESC LIMIT 0,5) AS s2 ON s2.id=s.id order by s.score desc