'how to get top 5 results from database along with all matched results

I want to show top 3 results and if is there are any results which match with top 3, they should also be fetched. In the examples below there are top 3 results, 50,40 and 30, but ram also has a mark of 30, so I want to fetch that result as well.

my database sheet table

id user marks
1 ram 30
3 sam 30
4 ben 40
2 hari 10
5 joe 50

i want to return top 3 results along with all matching results which is match to last result

id user marks
5 joe 50
4 ben 40
3 sam 30
1 ram 30
$top_results = "SELECT * FROM `sheet` ORDER BY `marks` DESC LIMIT 3"

and it only return top 3 not the 4 results

i want to show top 3 results and if is there any results match with top 3 also fetched, in above case there is top 3 results are 50,40 and 30 but ram has also 30. So I want to fetch that result also if it is their along with top 3



Solution 1:[1]

I want to show top 3 results and if is there are any results which match with top 3, they should also be fetched.

SELECT t1.*
FROM table t1
JOIN ( SELECT result
       FROM table t2
       ORDER BY result DESC LIMIT 2,1 ) t3 ON t1.result >= t2.result

how to get top 5 results from database along with all matched results

Adjust LIMIT accordingly - LIMIT 4,1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akina