MySQL的地方由平均子句和排序()作为一个子查询(MySQL where clause and o

2019-09-21 13:31发布

虽然我可以通过一个别名的子查询组和秩序,我不能在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

Answer 1:

您可以用HAVING子句要做到这一点,而不是一个WHERE的

句法



Answer 2:

我会做一个连接和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


文章来源: MySQL where clause and ordering by avg() as a sub query