I have table called \"users\" and need to select 2 rows before and after specific row, sorted by users.score ASC
users table (structure):
id name
Selecting arbitrarily ordered rows before and after a specific id
SET @j = 0;
SET @i = 0;
SELECT *
FROM (
SELECT id, col1, col2, ..., @j:=@j+1 AS pos
FROM `table`
WHERE col1=... ORDER BY col1 DESC, col2 ASC
) AS zz
WHERE (
SELECT position
FROM (
SELECT id AS id2, @i:=@i+1 AS position
FROM `table`
WHERE col1=... ORDER BY col1 DESC, col2 ASC
) AS zz
WHERE id2=$currId
)
IN (pos-5,pos-4,pos-3,pos-2,pos-1,pos,pos+1,pos+2,pos+3,pos+4,pos+5)