0

我有一个历史表,我需要检索每个资产 ID 的最后已知状态。这是我当前的查询:

SELECT a.AutoID AS AssetID, 
(SELECT LastFound FROM Device_Status_History b WHERE a.AutoID = b.AssetID ORDER BY AutoID DESC LIMIT 0,1)  LastFound,
(SELECT CheckDate FROM Device_Status_History c WHERE a.AutoID = c.AssetID ORDER BY AutoID DESC LIMIT 0,1) CheckDate
FROM (SELECT AutoID FROM Devices UNION SELECT AutoID FROM Switches) a

union 子查询获取我关心的所有资产 ID,然后我使用其他两个子查询从历史记录表中获取 LastFound 和 CheckDate 列。总的来说,这工作得很好,但如果可能的话,我希望能够组合两个历史子查询,甚至可能以某种方式使其成为连接,但我不知道如何在仍然使用限制的同时加入。我们在 Raspberry Pi 上运行它,因此我们希望能从中挤出每一盎司的性能。

4

1 回答 1

0

不知道它是否更快......但请尝试一下:

SELECT AssetID, LastFound, CheckDate
FROM Device_Status_History
WHERE AssetID IN (SELECT AutoID FROM Devices UNION SELECT AutoID FROM Switches)
AND AutoID IN (SELECT MAX(AutoID) FROM Device_Status_History GROUP BY AssetID);

另请注意,如果除了and表中的表之外,您的表中没有其他AssetID' ,则可以省略第三行,以便查询变为:Device_Status_HistoryDevicesSwitches

SELECT AssetID, LastFound, CheckDate
FROM Device_Status_History
WHERE AutoID IN (SELECT MAX(AutoID) FROM Device_Status_History GROUP BY AssetID);
于 2013-08-14T18:12:07.070 回答