Sql server 如何为这种逻辑编写sql?
我有以下表格(缩写)Sql server 如何为这种逻辑编写sql?,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我有以下表格(缩写) tableAssignments id timestamp // updated when row is modified tableSystems tableUsers ... tableAssignmentsSnapshot id timestamp // set when row created, snapshots never change tableS
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”是否是最新的,或者是否应该使用新的。所需的逻辑是:
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
您可以将第一个查询包装在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
仅供参考,时间戳是一个可怕的列名。它是一个保留字和一个数据类型(恰好与日期/时间没有任何关系)。