Return rows around my selection args (“surrounding rows”) in a database query
-
29-10-2019 - |
Question
I'm querying a database in Android. The table is your ordinary table with values, nothing special.
What I need: return the two events that happened before and after the given timestamp.
Example: let's suppose I have the table below, and my selection is 1332200003002:
_id | Time | Value
... ...
n | 1332200002000 | 145
n+1 | 1332200003001 | 98 (this is <= selection)
(1332200003002 is here, between those two)
n+2 | 1332200004000 | 90 (this is > selection)
n+3 | 1332200005000 | 100
n+4 | 1332200005001 | 280
So, if my selection is 1332200003001, or 1332200003002... I'd want the returned rows to be n+1 and n+2, so that I can see that the Value
went from 98 to 90.
What I'm using is a CursorLoader
, so it must preferably fit into its usual call.
My code size thanks you!
As a side note, I can guess safe values for BETWEEN
(it IS working already), and then iterate the few remaining Cursor
rows in Java to pinpoint the two rows that I need. However, this seems to me like a very common need, hence the question. Seems a waste to do it in Java with all those usual bumper tests we need to do with a Cursor.
Solution
SELECT *
FROM myTable LIMIT 2
OFFSET
(SELECT _id
FROM myTable
WHERE time<=1332200003002
ORDER BY time DESC LIMIT 1) - 1;
What this does:
Select 2 entries from the table. The offset of the first entry is selected as follows:
Choose the latest row where time <= 1332200003002
, and calculate its offset from the first row.
The -1
at the end is needed if your _id
values start at 1 rather than 0. (Change this value as needed to convert your _id
values into zero-based offsets.)