【问题标题】:MySQL where clause and ordering by avg() as a sub queryMySQL where 子句和 avg() 作为子查询的排序
【发布时间】:2009-07-30 21:05:09
【问题描述】:

虽然我可以对别名子查询进行分组和排序,但我不能在 where 子句中使用别名。我需要改用联接吗?

作品:

SELECT entries.*, 
    (SELECT avg(value) 
    FROM `ratings`
    WHERE ratings.entry_id = entries.id) as avg_rating
FROM `entries` 
ORDER BY avg_rating DESC

失败(“where 子句中的未知列 'avg_rating'”):

SELECT entries.*, 
    (SELECT avg(value) 
    FROM `ratings` 
    WHERE ratings.entry_id = entries.id) as avg_rating 
FROM `entries` 
WHERE avg_rating < '4.5000' ORDER BY avg_rating DESC

【问题讨论】:

    标签: mysql subquery where average clause


    【解决方案1】:

    您可以使用 HAVING 子句而不是 WHERE 来做到这一点

    Syntax

    【讨论】:

      【解决方案2】:

      我会做一个 join 和 groupby 例如,

      SELECT entries.*, AVG(value)
      FROM entries INNER JOIN ratings ON entries.id = ratings.entry_id 
      GROUP BY entries.*
      HAVING AVG(value) < '4.5000' 
      ORDER BY AVG(value)
      

      只是伪代码,我还建议您将条目列限制为您所需要的。

      您也许可以摆脱别名,例如:

      SELECT entries.*, AVG(value) as avg_value
      FROM entries INNER JOIN ratings ON entries.id = ratings.entry_id 
      GROUP BY entries.*
      HAVING avg_value < '4.5000' 
      ORDER BY avg_value
      

      【讨论】:

        猜你喜欢
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 2023-04-09
        • 1970-01-01
        • 2012-09-03
        • 2020-10-13
        • 1970-01-01
        相关资源
        最近更新 更多