我有两个查询得到:
当我UNION
查询时,我希望这两个测量值位于不同的列中,但它们实际上是在单独的(重复的)行中返回的。见下面的输出。
SELECT snowfall.cms as now_snow, resorts.*, regions.name
FROM snowfall
INNER JOIN resorts on resorts.id = snowfall.resort_id
INNER JOIN regions ON resorts.region_id = regions.id
WHERE snowfall.timestamp >= SUBDATE( NOW( ) , INTERVAL 1 HOUR )
GROUP BY resorts.id
UNION
SELECT snowfall.cms as 24hr_snow, resorts.*, regions.name
FROM snowfall
INNER JOIN resorts on resorts.id = snowfall.resort_id
INNER JOIN regions ON resorts.region_id = regions.id
WHERE snowfall.timestamp >= SUBDATE( NOW() , INTERVAL 1 DAY)
GROUP BY resorts.id
ORDER BY now_snow DESC
我得到的结果是:
now_snow | resorts.name | ... ======================================== 20 | The Mountain 15 | The Mountain 18 | The Hill 102 | The Hill
但是期待结果:
now_snow | 24hr_snow | resorts.name | ... ======================================== 20 | 15 | The Mountain 18 | 102 | The Hill
在这种情况下,UNION
是否正确?如何实现所需的输出?
答案 0 :(得分:2)
UNION
会在您的查询中添加行。为了扩大您的查询,您需要加入。
我建议在这种情况下自我加入。每天一次降雪,每小时降雪一次。两人都加入度假村id并按度假村名称分组。
SELECT sum(hourly.cms) as now_snow, sum(daily.cms) as 24hr_snow, resorts.name
FROM
snowfall daily
INNER JOIN resorts on resorts.id = daily.resort_id
INNER JOIN regions ON resorts.region_id = regions.id
INNER JOIN snowfall hourly on resorts.id = hourly.resort_id
WHERE daily.timestamp >= SUBDATE( NOW() , INTERVAL 1 DAY)
AND hourly.timestamp >= SUBDATE( NOW( ) , INTERVAL 1 HOUR )
GROUP BY resorts.name
ORDER BY now_snow DESC
你没有在你的帖子中使用聚合,mysql可能允许这样做,但为了清楚起见,我已经在这里添加了它。