I have the following tables (this is abbreviated)
tableAssignments
id
timestamp // updated when row is modified
tableSystems
tableUsers
...
tableAssignmentsSnapshot
id
timestamp // set when row created, snapshots never change
tableSystemsSnapshot
tableUsersSnapshot
tableAssignments_id // reference to "tableAssignments" row this was created from
syncKey // Changed when snapshots are created, max value is latest
Sometime after the tableAssignments are changed, snapshots of all the assignments are taken and the snapshots are created with the same syncKey. I am trying to write a query to check if the latest “tableAssignmentsSnapshot” are up to date or if new ones should be taken. The logic required is:
-
Determine the latest tableAssignmentSnapshots for each system, which is determine by maximum syncKey (see query below).
-
Join the result from #1 with tableAssignments.
- If timestamp from tableAssignments > timestamp from tableAssignmentsSnapshot then new snapshot is required.
The following query accomplishes step #1 and runs fast. It returns the tableAssignmentSnapshots with the greatest value of “syncKey” for each system.
select * from
tableAssignmentsSnapshot d inner join tableSystemsSnapshot e
on d.systemId = e.id
where d.syncKey = (select MAX(syncKey) from tableAssignmentsSnapshot y inner join tableSystemsSnapshot z
on y.systemId = z.id
where tableSystems_id = e.tableSystems_id)
I’m struggling with what to do next. I need to be able to do something like the following but am having trouble with the syntax required:
select * from tableAssignments a right outer join
(
the result from above query
)
on a.id = ?.tableAssignments_id
You could wrap your first query on a CTE: