I realize that I can do this in code, but I was curious if there’s a straight SQL way to select (for instance) 10 results in addition to the one that your query matches…
so, let’s say I had a database of players all of whom had scores and I wanted to show a user the 5 players whose scores are behind theirs and the 5 ahead… so, I select their row but now should I just use an or in the where clause and say something like…
select score as selectedScore from player_scores where playerId = xxxx
or (score > selectedScore - 5 and score < selectedScore + 5)
I realize that this implies all the scores are in exact order, and I’d modify the query to pull the userIds from those scores, so this is just a pseudo example for the sake of the question.
I suspect that would work, but is that the *right way to approach this?
You can use
UNIONto combine two queries that useORDER BYandLIMITto select the next 5 and the previous 5 respectively; by using a self-join in each query, one can find all other players adjacent to the desired player’s score (this assumes thatplayerIdis unique inplayer_scoreshowever):