Skip to content
Advertisement

MySQL get rows starting with specific id after sort / order by

I got this table:

id | score
1  | 1
2  | 4
3  | 4
4  | 3
5  | 2
6  | 2
7  | 1
8  | 4
9  | 2
10 | 3

I need to order it by score desc:

id | score
2  | 4
3  | 4
8  | 4
4  | 3
10 | 3
5  | 2
6  | 2
9  | 2
1  | 1
7  | 1

and get first 3 rows which starts with id 6

So the result should be:

6  | 2
9  | 2
1  | 1

Is this possible? Thanks in advance

Advertisement

Answer

With this:

select t.*
from tablename t cross join (select * from tablename where id = 6) c
where t.score < c.score or (t.score = c.score and t.id >= c.id)
order by t.score desc, t.id
limit 3

See the demo.
Results:

| id  | score |
| --- | ----- |
| 6   | 2     |
| 9   | 2     |
| 1   | 1     |
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement