我有以下表格(缩写)
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
更改tableAssignments后的某个时间,将执行所有分配的快照,并使用相同的syncKey创建快照。我正在尝试编写一个查询来检查最新的“tableAssignmentsSnapshot”是否是最新的,或者是否应该采用新的。所需的逻辑是:
确定每个系统的最新tableAssignmentSnapshots,由最大syncKey确定(请参阅下面的查询)。
使用tableAssignments加入#1的结果。
以下查询完成步骤#1并快速运行。它返回tableAssignmentSnapshots,每个系统的最大值为“syncKey”。
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)
我正在努力做下一步该做什么。我需要能够执行以下操作,但遇到所需语法的问题:
select * from tableAssignments a right outer join
(
the result from above query
)
on a.id = ?.tableAssignments_id
答案 0 :(得分:0)
您可以将您的第一个查询包装在CTE上:
;WITH CTE AS
(
SELECT * -- Here you should list only the columns that you are gonna need
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)
)
SELECT *
FROM tableAssignments A
RIGHT JOIN CTE B
ON A.id = B.tableAssignments_id