I have an Events table with a not-null date field. Based on a pivot date and an offset, the query must return the next 2 events.
Here’s the query I’m trying to build:
SELECT e.* FROM Events as e
JOIN (
-- latest event before pivot date, with offset
SELECT * FROM Events where date < :dateRef
ORDER BY date DESC, id DESC LIMIT :offset,1
) as eLatest
-- depending on :dateRef and :offset, eLatest can be empty!
-- If eLatest is empty, the join should produce all rows from Events table.
-- "eLatest is null" gives an error... How can I do it?
ON e.date > eFirst.date || (e.date = eFirst.date && e.id >= eFirst.id)
ORDER BY e.date, e.id LIMIT 2
With the following events sequence when sorted by date ASC (no equal dates to keep it simple) :
e0 – e1 – e2 – … – e10
here are some desired results:
- :dateRef = e2.date, :offset = 0 : [e1, e2]
- :dateRef = e2.date, :offset = 1 : [e0, e1]
- :dateRef = e2.date, :offset > 1 : [e0, e1] <— Does not work, returns no row
- :dateRef <= e0.date, :offset = ? : [e0, e1] <— Does not work, returns no row
- :dateRef = e5.date, :offset = 2 : [e2, e3]
- :dateRef > e10.date, :offset = 0 : [e10]
- :dateRef > e10.date, :offset = 2 : [e8, e9]
The problem I have is that when the subquery eLatest is empty, the join never matches. I can’t figure out how to drop the join condition when eLatest is empty.
The final query must be doable in JPQL or JPA criteria (so no UNIONS! I already have a query that works with a UNION and am trying to get rid of it…)
Would a RIGHT JOIN solution do?