我有一个SQL Server 2008实例,它承载多个数据库,每个客户端一个。他们每个人都有一张日志表。我希望从最近保存到的最新数据库日志中查看最新日志条目中的前20行。
以下是仅使用两个数据库进行尝试的示例。我觉得有一种更好的方法(我将WHERE
子句放入以帮助提高性能,因为日志表中有数百万行)
SELECT TOP 10
*
FROM
( SELECT TOP 10
B.Description,
B.Created,
B.Type,
B.MachineName
FROM
[BAB].[dbo].[PatientActivityLog] B
WHERE
B.Created > (GETDATE() - 1)
UNION
SELECT TOP 10
C.Description,
C.Created,
C.Type,
C.MachineName
FROM
[BAC].[dbo].[PatientActivityLog] C
WHERE
C.Created > (GETDATE() - 1)
) x
ORDER BY
x.Created DESC
感谢您的帮助。
答案 0 :(得分:1)
使用UNION ALL
代替UNION
以避免重复检查。还可以在TOP 20
子查询中添加订单。
SELECT TOP 20 *
FROM(
SELECT TOP 20
Description, Created, Type, MachineName
FROM [BAB].[dbo].[ActivityLog]
WHERE Created > (GETDATE() - 1)
ORDER BY Created DESC
UNION ALL
SELECT TOP 20
Description, Created, Type, MachineName
FROM [BAC].[dbo].[ActivityLog]
WHERE Created > (GETDATE() - 1)
ORDER BY Created DESC
) x
ORDER BY
x.Created DESC