使用group by的mysql异常查询

时间:2011-12-31 12:06:53

标签: mysql

我使用下面的查询来检测平均雪坡和最小雪度之间的10厘米差异。但PhpMyadmin表示这是对群组功能的无效使用。看不出有什么不对。你知道吗?

SELECT lud, res_id, resort, 
MIN(snow_valley) as snow_val_min, 
MAX(snow_valley) as snow_val_max,
ROUND(AVG(snow_mountain),0) as snow_mnt_avg, 
MIN(snow_mountain) as snow_mnt_min
from sv_condition_sw 
where (lud ='2011-12-31')  AND (AVG(snow_mountain)-MIN(snow_mountain)>10) GROUP by res_id

2 个答案:

答案 0 :(得分:2)

select with with group by中的每一列都必须汇总或包含在group by中。聚合表达式的条件必须出现在having子句中,如下所示:

SELECT lud, res_id, resort, 
MIN(snow_valley) as snow_val_min, 
MAX(snow_valley) as snow_val_max,
ROUND(AVG(snow_mountain),0) as snow_mnt_avg, 
MIN(snow_mountain) as snow_mnt_min
from sv_condition_sw 
where (lud ='2011-12-31')
GROUP by lud, res_id, resort
HAVING AVG(snow_mountain)-MIN(snow_mountain)>10

答案 1 :(得分:0)

错误的原因是SQL查询的执行顺序为FROM - > WHERE - > GROUP BY - > HAVING - > SELECT - > ORDER BY。因此,AVG()之前的MIN()WHERE不会在GROUP BY之后进行评估。

HAVING中使用具有aggreagte功能的条件,而不是WHERE

SELECT lud, res_id, resort, 
    MIN(snow_valley) AS snow_val_min, 
    MAX(snow_valley) AS snow_val_max,
    ROUND(AVG(snow_mountain),0) AS snow_mnt_avg, 
    MIN(snow_mountain) AS snow_mnt_min
FROM sv_condition_sw 
WHERE (lud ='2011-12-31')  
GROUP by res_id
HAVING (AVG(snow_mountain)-MIN(snow_mountain)>10)