【问题标题】:Invalid use of group function when i use avg with count and sum当我将 avg 与 count 和 sum 一起使用时,组函数的使用无效
【发布时间】:2018-01-10 20:30:23
【问题描述】:

我的查询有什么问题?

select p.name, p.photo, (
        SELECT AVG(count(ra.id_prof)/sum(ra.rate))
        FROM  rating ra
        WHERE  ra.id_prof = p.id) as rating  
from prof_table p, matier_prof mp, matiere m, niveau ni
where p.id=mp.id_prof and mp.id_matiere=m.id_mat and m.id_niv=ni.id_niv
having p.name like '%word%' or p.email like '%word%' or p.adresse like '%word%' or 
    p.biographie like '%word%' or m.matiere like '%word%' or ni.niveau like '%word%'

【问题讨论】:

  • 用样本数据和期望的结果提出另一个问题。您的查询毫无意义。
  • 不能将一个聚合函数的结果放到另一个聚合函数中:avg(count()/sum())
  • 您的查询有几个问题。首先,您使用的是 1992 年变得多余的旧连接语法(逗号分隔连接)。为什么要使用它?然后你聚合(COUNT,SUM),但是为什么要聚合聚合(AVG)?然后,您在尚未分组且也不是聚合的列上使用 HAVING 子句。最好按照戈登的建议去做;告诉我们您想要达到的目标。这可能相当简单。
  • @ThorstenKettner 非常感谢你的评论有答案问题是 AVG 这是一个愚蠢的错误谢谢你,我很抱歉这个愚蠢的问题
  • 看起来双重聚合的尝试是这里最大的问题(因为它会导致错误)。旧的 JOIN 样式语法很难看,但会运行。 HAVING 子句毫无意义,所有这些条件都应移至 WHERE 子句。示例数据和所需结果将帮助我们引导您找到可行的解决方案。

标签: mysql sql average


【解决方案1】:

我已经在您的请求的 cmets 部分提到了您的问题。这可能是您所追求的:从 prof_table 中选择可以在其中一列中找到该词或存在匹配的 matiere 或 niveau。

select 
  p.name, 
  p.photo, 
  (select avg(ra.rate) from rating ra where ra.id_prof = p.id) as rating  
from prof_table p
where p.name like '%word%' 
or p.email like '%word%' 
or p.adresse like '%word%' 
or p.biographie like '%word%' 
or p.id in
(
  select mp.id_prof 
  from matier_prof mp
  join matiere m on m.id_mat = mp.id_matiere
  left join niveau ni on ni.id_niv = m.id_niv
  where m.matiere like '%word%' or ni.niveau like '%word%'
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多