I have a simple parent - child (one to many related) tables. Here is a simplified example where I'm tracking trains and their locations.
Table TRAIN
- ID
- NAME
Table TRAIN_STATUS
- ID
- TRAIN_ID (fk)
- STATION_CD
- ARRIVAL_TIME
Every time a train reached a station, a new record will be inserted in TRAIN_STATUS with the corresponding STATION_CD and ARRIVAL_TIME (timestamp)
Given a train id, I want to be able to tell what was the last known station of the train:
The SQL solution: - using a combination of derived table and correlated sub-query
select t.ID, t.name, recent.STATION_CD
from TRAIN t
join (
select TRAIN_ID, STATION_CD
from TRAIN_STATUS ts
where ts.ARRIVAL_TIME = (
select MAX(ARRIVAL_TIME) from TRAIN_STATUS where TRAIN_STATUS.TRAIN_ID = ts.TRAIN_ID
)
) recent on t.ID=recent.TRAIN_ID
where t.ID = 1;
I couldn't put together an equivalent in jOOQ. Any help will be much appreciated.
EDIT: Dialect is MySQL (5.7). Posting my own answer @LukasEder's advise.