我最近偶然发现这个线程,用户试图根据另一个查询的最大值使用子查询返回一些数据,Original Post这正是我想要做的。
我要做的是从我的审计表“Modification_Log”中提取最新的日志条目,以便列出最近的更改日期,以及比检索多个查询更优雅的方式。我已经在这里详细了解了Database Administrator's Stack,我不是要求用汤匙喂食,但我根本不知道出了什么问题!
SELECT Employee.EmployeeID, Employee.PositionID, Employee.Title, Employee.Firstname, Employee.Surname, Employee.Email, Modification_Log.ModifiedDate, Modification_Log.ModifiedEmployee
FROM Employee INNER JOIN Modification_Log ON Employee.EmployeeID = Modification_Log.RecordID INNER JOIN
(SELECT Modification_Log.RecordID, Max(Modification_Log.ModificationID) As NewestModificationID
FROM Modification_Log
GROUP BY Modification_Log.RecordID) As LogMax
ON Employee.EmployeeID = LogMax.RecordID AND Modification_Log.ModificationID = LogMax.NewestModificationID
WHERE Employee.EmployeeID = 3 AND Modification_Log.TableName = 'Employee'
编辑:我按照下面提到的@maxhugen做了,瞧瞧..访问它的无限智慧重新排列查询以首先引用连接的查询,我已经编辑了它并再次用子查询替换,这个时间有效:
SELECT Employee.EmployeeID, Employee.PositionID, Employee.Title, Employee.Firstname, Employee.Surname, Employee.Email, Modification_Log.ModifiedDate, Modification_Log.ModifiedEmployee
FROM
(SELECT Modification_Log.RecordID, Max(Modification_Log.ModificationID) As NewestModificationID
FROM Modification_Log
GROUP BY Modification_Log.RecordID) As LogMax
INNER JOIN (Employee INNER JOIN Modification_Log ON Employee.EmployeeID = Modification_Log.RecordID) ON (LogMax.NewestModificationID = Modification_Log.ModificationID) AND (LogMax.RecordID = Employee.EmployeeID)
WHERE Employee.EmployeeID=3 AND Modification_Log.TableName='Employee';
答案 0 :(得分:1)
我无法在您的sql中发现错误,但会建议:
一旦确保它运行正常,您可以使用它的SQL作为主查询sql中的子查询来替换(1)中的查询。