I’ve got four tables: A, B, C, D. D has a FK to C, C has a FK to B, B has a FK to A. Each table has an ID column. In addition to ID and CID, table D has Value and Timestamp (an integer). Given a certain time, I need the row from D before the Timestamp but closest to it for each CID — Unless there are no rows before the Timestamp, in which case I need the first value after after the Timestamp. I’m using Sqlite.
Leaving out this last requirement, I attempted to get the values before the Timestamp with this query, but the ID returned is wrong:
SELECT *
FROM D d
INNER JOIN C c ON d.CID = c.ID
INNER JOIN B b ON C.BID = b.ID
WHERE b.AID = @AID AND d.Timestamp =
(
SELECT MAX(d2.Timestamp)
FROM D d2
WHERE d2.Timestamp < @StartTime
AND d2.CID = D.CID
)
This query should get the last entry before @StartTime in the first part of the query (before the UNION ALL) then combine it with the first entry after @StartTime. All that remains is to pick the smallest entry for each CID.