我们使用监控解决方案(zabbix)。它使用名为trends_uint的表存储趋势数据(MySQL 5.X),其结构如下(简化):
itemid clock value_avg
1 1238774400 100
1 1250773900 70
1 1250773200 50
时钟字段使用Unix时间存储日期时间值。
我正在尝试提取报告以查看受监控项目的消耗情况。我想通过选择最早的记录和最新的记录来做到这一点。我实现了以下目标:
SELECT
(SELECT t.clock FROM trends_uint t WHERE t.itemid = 1 AND t.clock IN (SELECT MIN(t.clock) FROM trends_uint t WHERE t.itemid = 1)) AS minClock,
(SELECT t.value_avg FROM trends_uint t WHERE t.itemid = 1 AND t.clock IN (SELECT MIN(t.clock) FROM trends_uint t WHERE t.itemid = 1)) AS minValueAvg,
(SELECT t.clock FROM trends_uint t WHERE t.itemid = 1 AND t.clock IN (SELECT MAX(t.clock) FROM trends_uint t WHERE t.itemid = 1)) AS maxClock,
(SELECT t.value_avg FROM trends_uint t WHERE t.itemid = 1 AND t.clock IN (SELECT MAX(t.clock) FROM trends_uint t WHERE t.itemid = 1)) AS maxValueAvg,
(SELECT maxClock - minClock) AS timeGap,
(SELECT minValueAvg - maxValueAvg) AS valueGap,
(SELECT timeGap/86400) AS daysGap,
(SELECT valueGap/daysGap/1024/1024) AS consumeMB
我的问题是我有很多服务器,我想从中计算消耗量。我不想更改哪一个查询(更改itemid)。
系统有另一个表(项),我可以从中提取我需要放入报表的项目。像SELECT itemid FROM items WHERE ...
所以这是我的问题:不是使用硬编码的itemid,而是可以使其“动态”,例如使用来自其他查询的返回代码(例如:SELECT ... FROM ... WHERE itemid IN (SELECT itemid FROM items WHERE ...
)?
TIA,
鲍勃
答案 0 :(得分:1)
看起来您想要的是使用您的编程语言或MySQL user-defined变量来存储您选择的ID并重复使用它。
我假设您正在使用某种语言(例如PHP)来绕过这些调用。
然后你可以:
使用MySQL用户定义的变量并保存itemid,类似于
SET @ itemid = SELECT itemid FROM trends_uint WHERE ....
SELECT .... WHERE t.itemid = @itemid ....
答案 1 :(得分:0)
答案 2 :(得分:0)
select id,
min(clock) as minClock,
max(clock) as maxClock,
maxClock - minClock as timeGap,
(timeGap/86400) AS daysGap,
min(value_avg) as minValueAvg,
max(value_avg) as maxValueAvg,
(valueGap/daysGap/1024/1024) AS consumeMB
from trends_uint
group by id;
那应该立即完成所有这些。
将来,如果你确实需要一些东西作为一个循环(虽然它在我看来这样做更好,作为一个带有“group by”的单个语句,引用是http://dev.mysql.com/doc/refman/5.0/en/flow-control-constructs.html