I want to be able to target one record, and get back that record, and a variable amount of records on each side of it.
Like say you have a key id of 2356. So you need 2356 and the 3 records before and after 2356, with an order by on create_ts (for example).
I am wondering if there is a way to do this in one query (mysql)?
The table (call it mytable) has to have a compound index on create_ts and id
You evidently need two queries to pick up needed keys: 3 before id, the id itself, 3 after id.
That’s 7 ids.
This query picks up 4 keys (id + 3 after)
This query picks up 4 keys (id + 3 before)
A UNION of the two queries should eliminate a duplicate of id 2356
Let’s combine these and perform an INNER JOIN of it to mytable
The subquery A should only have 7 keys. Once those 7 keys are retrieved, the INNER JOIN should be quick.
Whenever you need N keys before and N keys after for this query, just use
LIMIT N+1.I would suggest this method because we can neither assume that 3 keys back is id-3, nor assume 3 keys after is id+3. This is especially true if the table has gaps in the ids for any reason.
Give it a Try !!!
CAVEAT : I did not try it out. This is what you want algorithmically. The MySQL syntax may or may not allow for it. It the syntax is not right, I’ll try to construct an example and fix the syntax.
Just in case, here is a more stable approach.