联合所有相同的查询两次返回null

时间:2014-09-12 13:16:46

标签: mysql sql

我有以下查询返回类似' top' - > ' 30',' metrictype' - > &#c; cpu usage' (该查询计算20%最重的运行机器的平均CPU / MEM使用率。

SELECT   round(avg(avgcpuusage)) as 'top', metrictype
FROM    
    (  
SELECT (vmstatstemp.avgcpuusage),
    vmstatstemp.vmname,
    vmstatstemp.metrictype,
    @counter := @counter +1 AS counter
    FROM (select @counter:=0) AS initvar,  (select round(avg(vmstats.metricvalue)) as 'avgcpuusage', vmstats.vmname,
    vmstats.metrictype from vmstats   
    join vms on vms.naam = vmstats.vmname
    join klanten on vms.klant = klanten.ID
    where metrictype = 'cpu usage'
    AND SUBSTRING(vmstats.dataEntryTimestamp,4,7)  = date_format(now(),'%m:%Y')
    group by vmname
    order by avgcpuusage desc) vmstatstemp
    ) as temp
where counter < round(0.2* (@counter+1))

如果我将此查询与其自身结合(见下文),我会得到以下结果:

&#39;顶部&#39; - &GT; &#39; 30&#39;,&#39; metrictype&#39; - &GT; &#c; cpu usage&#39; &#39;顶部&#39; - &GT; &#39; null&#39;,&#39; metrictype&#39; - &GT; &#39;空&#39;

    SELECT   round(avg(avgcpuusage)) as 'top', metrictype
FROM    
    (  
SELECT (vmstatstemp.avgcpuusage),
    vmstatstemp.vmname,
    vmstatstemp.metrictype,
    @counter := @counter +1 AS counter
    FROM (select @counter:=0) AS initvar,  (select round(avg(vmstats.metricvalue)) as 'avgcpuusage', vmstats.vmname,
    vmstats.metrictype from vmstats   
    join vms on vms.naam = vmstats.vmname
    join klanten on vms.klant = klanten.ID
    where metrictype = 'cpu usage'
    AND SUBSTRING(vmstats.dataEntryTimestamp,4,7)  = date_format(now(),'%m:%Y')
    group by vmname
    order by avgcpuusage desc) vmstatstemp
    ) as temp
where counter < round(0.2* (@counter+1))


union all


SELECT   round(avg(avgcpuusage)) as 'top', metrictype
FROM    
    (  
SELECT (vmstatstemp.avgcpuusage),
    vmstatstemp.vmname,
    vmstatstemp.metrictype,
    @counter := @counter +1 AS counter
    FROM (select @counter:=0) AS initvar,  (select round(avg(vmstats.metricvalue)) as 'avgcpuusage', vmstats.vmname,
    vmstats.metrictype from vmstats   
    join vms on vms.naam = vmstats.vmname
    join klanten on vms.klant = klanten.ID
    where metrictype = 'cpu usage'
    AND SUBSTRING(vmstats.dataEntryTimestamp,4,7)  = date_format(now(),'%m:%Y')
    group by vmname
    order by avgcpuusage desc) vmstatstemp
    ) as temp
where counter < round(0.2* (@counter+1))

我不明白为什么我的结果是 &#39;顶部&#39; - &GT; &#39; 30&#39;,&#39; metrictype&#39; - &GT; &#c; cpu usage&#39; &#39;顶部&#39; - &GT; &#39; null&#39;,&#39; metrictype&#39; - &GT; &#39;空&#39; 代替 &#39;顶部&#39; - &GT; &#39; 30&#39;,&#39; metrictype&#39; - &GT; &#c; cpu usage&#39; &#39;顶部&#39; - &GT; &#39; 30&#39;,&#39; metrictype&#39; - &GT; &#39; cpu usage&#39;, 任何人都能解释一下吗? (并提出如何获得正确结果的建议?)

1 个答案:

答案 0 :(得分:1)

正如Gordon Linoff指出的那样:你需要为两个子查询使用不同的变量