需要MySQL中子查询的顶行中的多个字段

时间:2013-08-14 17:55:24

标签: mysql

我有一个历史记录表,我需要检索每个资产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上运行它,所以我们可以从中挤出每一盎司的性能。

1 个答案:

答案 0 :(得分: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);

另请注意,如果除了AssetIDDevice_Status_History表格中的Devices表之外,Switches表中没有其他SELECT AssetID, LastFound, CheckDate FROM Device_Status_History WHERE AutoID IN (SELECT MAX(AutoID) FROM Device_Status_History GROUP BY AssetID); ,则可以省略第三行,以便查询变为:

{{1}}