SQLite: select X records around a row with a certain ID according to ORDER statement
I know can select the next or previous X records with statements like the following:
Next: `SELECT * FROM table WHERE some_key > 3 ORDER BY some_key ASC LIMIT X`
Previous: `SELECT * FROM table WHERE some_key < 3 ORDER BY some_key DESC LIMIT X`
However I开发者_如何学Python'm working in a language which returns a Cursor over the results and I'd like all of my results in one cursor.
Is it possible to select the current record, along with X next and previous records in a single SQL statement?
You could try using a UNION:
SELECT * FROM table WHERE some_key > 3 ORDER BY some_key ASC LIMIT X
UNION
SELECT * FROM table WHERE some_key = 3
UNION
SELECT * FROM table WHERE some_key < 3 ORDER BY some_key DESC LIMIT X
You might need to fix up the ordering outside the unions but the above will give you the window around some_key = 3
that you're looking for and it will cleanly deal with gaps in the some_key
values.
In the end I used the answer from @mu, with some modifications
In Android, you cannot use inner ORDER BY
statements in a UNION
, just a single outer ORDER BY
on the whole set. To get around this I used the fact that SQLite on Android does support inner queries, performed each actual select in an inner query and then selected all rows from the inner query to union, as follows:
SELECT * FROM (SELECT * FROM table WHERE some_key > 3 ORDER BY some_key ASC LIMIT X)
UNION
SELECT * FROM table WHERE some_key = 3
UNION
SELECT * FROM (SELECT * FROM table WHERE some_key < 3 ORDER BY some_key DESC LIMIT X)
精彩评论