如何为两个表使用max

时间:2019-05-08 06:29:31

标签: mysql

我想在时间字段上使用MAX,它可以工作,但是值是“ 0”

此查询是在我使用MAX之前进行的:

SELECT a.`JAM`, AVG(a.PacketLoss) AVG
FROM (
SELECT `JAM`,`RNC`,`IPPATH_PM` AS PHB,`VS_IPPM_FORWORD_DROPMEANS` AS PacketLoss, `VSIPPMRttMeans` AS Latency, 'IPPM'
FROM `rnc_ippm_meas`
WHERE `JAM`>= CURDATE() AND `IPPATH_PM` LIKE '%AF31%'
UNION
SELECT `JAM`,`RNC`,`IPPOOL_PM`,`VSIPPOOLIPPMForwardDrop-Means`,`VSIPPOOLIPPMRttMeans`, 'IPPOOLPM'
FROM `rnc_ippool_ippm_meas` 
WHERE `JAM`>= CURDATE() AND `IPPOOL_PM` LIKE '%AF31%') a
GROUP BY a.`JAM`
LIMIT 10000 

在这里输出

output1

然后我在这里使用MAX

SELECT a.`JAM`, AVG(a.PacketLoss) AVG
FROM (
SELECT MAX(JAM) AS JAM,`RNC`,`IPPATH_PM` AS PHB,`VS_IPPM_FORWORD_DROPMEANS` AS PacketLoss, `VSIPPMRttMeans` AS Latency, 'IPPM'
FROM `rnc_ippm_meas`
WHERE `JAM`>= CURDATE() AND `IPPATH_PM` LIKE '%AF31%'
UNION
SELECT MAX(JAM) AS JAM,`RNC`,`IPPOOL_PM`,`VSIPPOOLIPPMForwardDrop-Means`,`VSIPPOOLIPPMRttMeans`, 'IPPOOLPM'
FROM `rnc_ippool_ippm_meas` 
WHERE `JAM`>= CURDATE() AND `IPPOOL_PM` LIKE '%AF31%') a
GROUP BY a.`JAM`
LIMIT 10000

output2

我希望输出是最后一次输入的值,有人可以帮助我吗?谢谢

1 个答案:

答案 0 :(得分:2)

您需要在外部查询而不是内部查询上使用MAX。当您对内部查询进行处理时,MySQL为您提供了非聚合列的不确定值,例如VS_IPPM_FORWORD_DROPMEANS,对于您的示例数据,它似乎是一个0值。将查询更改为:

SELECT MAX(a.`JAM`), AVG(a.PacketLoss) AVG
FROM (
SELECT `JAM`,`RNC`,`IPPATH_PM` AS PHB,`VS_IPPM_FORWORD_DROPMEANS` AS PacketLoss, `VSIPPMRttMeans` AS Latency, 'IPPM'
FROM `rnc_ippm_meas`
WHERE `JAM`>= CURDATE() AND `IPPATH_PM` LIKE '%AF31%'
UNION
SELECT `JAM`,`RNC`,`IPPOOL_PM`,`VSIPPOOLIPPMForwardDrop-Means`,`VSIPPOOLIPPMRttMeans`, 'IPPOOLPM'
FROM `rnc_ippool_ippm_meas` 
WHERE `JAM`>= CURDATE() AND `IPPOOL_PM` LIKE '%AF31%') a

请注意,由于您要在整个数据集中使用GROUP BYMAX,因此不再需要AVG,并且此查询不需要LIMIT只会产生1行。