MySQL where clause and ordering by avg() as a sub query

Deadly 提交于 2019-12-14 02:18:47

问题


Although I can group and order by on an aliased sub query, I can't use the alias in a where clause. Do I need to use a join instead?

Works:

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

Fails ("unknown column 'avg_rating' in where clause"):

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

回答1:


You may be able to do this with a HAVING clause instead of a WHERE

Syntax




回答2:


I would do a join and groupby For example,

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)

Just psuedo code, I would also recommend you limit the entries columns to exactly what you need.

You might be able to get away with the alias such as:

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


来源:https://stackoverflow.com/questions/1209364/mysql-where-clause-and-ordering-by-avg-as-a-sub-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!