MySQL: select 5 rows before and after specific row

后端 未结 5 521
陌清茗
陌清茗 2020-12-20 23:26

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         


        
5条回答
  •  一个人的身影
    2020-12-21 00:13

    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)
    

提交回复
热议问题