开发者

Negative limit offset in mysql

开发者 https://www.devze.com 2023-01-29 06:34 出处:网络
I\'m creating a high score server and one of the needed features is being able to retrieve high scores around the users current score. I currently have the following:

I'm creating a high score server and one of the needed features is being able to retrieve high scores around the users current score. I currently have the following:

SELECT * FROM highscores 
WHERE score >= ( SELECT score FROM highscores WHERE userID = someID ) 
ORDER BY score, updated ASC 
LIMIT -9, 19

The only problem here is that the offset parameter of LIMIT can't be negative, otherwise I believe this would work dandy. So in conclusion, is there any tric开发者_如何学Pythonk / way to supply a negative offset to the LIMIT offset, or is there perhaps a better way to about this entirely?


You can either do a real pain in the butt single select query, or just do this:

(SELECT * FROM highscores 
WHERE score <= ( SELECT score FROM highscores WHERE userID = someID ) 
ORDER BY score, updated ASC 
LIMIT 9)
UNION
(SELECT * FROM highscores 
WHERE score = ( SELECT score FROM highscores WHERE userID = someID ))
UNION 
(SELECT * FROM highscores 
WHERE score >= ( SELECT score FROM highscores WHERE userID = someID ) 
ORDER BY score, updated ASC
LIMIT 9)

I threw in a piece to grab the indicated user's score so it's in the middle of the list. Optional if you need it. Also, don't use SELECT *, use specific fields. Clarity is always preferable, and performance wise, * sucks.

0

精彩评论

暂无评论...
验证码 换一张
取 消