I have a table named scores
with the columns id
and score
. I want to access a specific record by its id
as well as the 5 records before and after it. Is there a way in SQL to say "grab the score with the id of n
and x
items before and after it?"
views:
42answers:
1
+1
A:
Try:
SELECT *
FROM scores
WHERE score >= n
ORDER BY score ASC
LIMIT 6
UNION
SELECT *
FROM scores
WHERE score < n
ORDER BY score DESC
LIMIT 5
The syntax may vary somewhat depending upon what Database server you are using.
Justin Ethier
2010-03-17 01:54:14
I think you may want `LIMIT 6` for the `>=` part of the union.
spong
2010-03-17 01:56:41
Good point, thanks.
Justin Ethier
2010-03-17 01:58:06
Thanks Justin - this is exactly what I was looking for. As a side note those select statements have to be wrapped in parens (at least for MySQL).
richleland
2010-03-17 02:55:59