对于下面的查询,我正在尝试检索lastheatbeattime
大于10的计算机列表。我希望每次运行查询时都返回相同的结果。目前,下面的代码多次检索相同的结果,然后进行更改。
我对SQL不是很有经验,所以简单的回答是可取的。
SELECT
COUNT(*) AS TestValue,
locations.name AS IDentityField,
(SELECT c.computerid FROM computers ORDER BY c.computerid DESC LIMIT 1) AS ComputerID,
locations.locationid AS LocationID,
acd.NoAlerts,
acd.UpTimeStart,
acd.UpTimeEnd
FROM
Computers c
JOIN AgentComputerData acd
ON (c.computerid = acd.computerid)
JOIN heartbeatcomputers
ON c.Computerid = heartbeatcomputers.computerid
JOIN locations
ON c.`LocationID` = locations.`LocationID`
JOIN v_extradatalocations
ON c.`LocationID` = v_extradatalocations.`locationid`
WHERE c.os LIKE '%Windows Server%'
AND LastHeartbeatTime < DATE_ADD(NOW(), INTERVAL - 10 MINUTE)
AND v_extradatalocations.`Server Service Plan` LIKE "%Managed 24x7%"
AND locations.locationid != 154
GROUP BY c.`LocationID`
HAVING COUNT(DISTINCT c.computerid) > 1
AND COUNT(DISTINCT c.`ClientID`) < 20;
答案 0 :(得分:0)
如果添加ORDER BY
子句,则可以使结果更具确定性 - 如果没有这个,则顺序是随机的(通常与SQL可以执行查询的最快方式相关)。
答案 1 :(得分:0)
仔细观察,你想要这样做:
SELECT
COUNT(*) AS TestValue,
locations.name AS IDentityField,
c.computerid AS ComputerID,
locations.locationid AS LocationID,
acd.NoAlerts,
acd.UpTimeStart,
acd.UpTimeEnd
FROM
Computers c
JOIN AgentComputerData acd
ON (c.computerid = acd.computerid)
JOIN heartbeatcomputers
ON c.Computerid = heartbeatcomputers.computerid
JOIN locations
ON c.`LocationID` = locations.`LocationID`
JOIN v_extradatalocations
ON c.`LocationID` = v_extradatalocations.`locationid`
WHERE c.os LIKE '%Windows Server%'
AND LastHeartbeatTime < DATE_ADD(NOW(), INTERVAL - 10 MINUTE)
AND v_extradatalocations.`Server Service Plan` LIKE "%Managed 24x7%"
AND locations.locationid != 154
GROUP BY c.`LocationID`
HAVING COUNT(DISTINCT c.computerid) > 1
AND COUNT(DISTINCT c.`ClientID`) < 20
ORDER BY c.computerid DESC;
你的嵌套选择是抓取一个随机行,因为没有任何内容可以将它与查询的其余部分联系起来。
答案 2 :(得分:0)
答案很简单..将max()添加到c.computerid AS ComputerID, 例如。 MAX(c.computerid)AS ComputerID,
这是因为我混合了分组和未分组的列,因此sql返回“随机”数据。
来源:jkavalik - #mysql freenode IRC
谢谢, 贾斯汀